示例#1
0
/**
 * CURL发送请求
 *
 * @param string $url
 * @param mixed $data
 * @param string $method
 * @param string $cookieFile
 * @param array $headers
 * @param int $connectTimeout
 * @param int $readTimeout
 */
function curlRequest($url, $data = '', $method = 'POST', $cookieFile = '', $headers = ['Content-Type: application/json'], $connectTimeout = 30, $readTimeout = 30)
{
    $method = strtoupper($method);
    if (!function_exists('curl_init')) {
        return socketRequest($url, $data, $method, $cookieFile, $connectTimeout);
    }
    $option = array(CURLOPT_URL => $url, CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => $connectTimeout, CURLOPT_TIMEOUT => $readTimeout);
    if ($headers) {
        $option[CURLOPT_HTTPHEADER] = $headers;
    }
    if ($cookieFile) {
        $option[CURLOPT_COOKIEJAR] = $cookieFile;
        $option[CURLOPT_COOKIEFILE] = $cookieFile;
        //$option[CURLOPT_COOKIESESSION] = true;
        //$option[CURLOPT_COOKIE] = 'prov=42;city=1';
    }
    if ($data && $method == 'POST') {
        $option[CURLOPT_POST] = 1;
        $option[CURLOPT_POSTFIELDS] = $data;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    if (curl_errno($ch) > 0) {
        return null;
    }
    curl_close($ch);
    return $response;
}
示例#2
0
/**
 * @param string $url
 * @param mixed $data
 * @param string $method
 * @param string $cookieFile
 * @param array $headers
 * @param int $connectTimeout
 * @param int $readTimeout
 */
function curlRequest($url, $data = '', $method = 'POST', $cookieFile = '', $headers = '', $connectTimeout = 30, $readTimeout = 30)
{
    $method = strtoupper($method);
    if (!function_exists('curl_init')) {
        return socketRequest($url, $data, $method, $cookieFile, $connectTimeout);
    }
    $option = array(CURLOPT_URL => $url, CURLOPT_HEADER => 0, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => $connectTimeout, CURLOPT_TIMEOUT => $readTimeout);
    if ($headers) {
        $option[CURLOPT_HTTPHEADER] = $headers;
    }
    if ($cookieFile) {
        $option[CURLOPT_COOKIEJAR] = $cookieFile;
        $option[CURLOPT_COOKIEFILE] = $cookieFile;
    }
    if ($data && strtolower($method) == 'post') {
        $option[CURLOPT_POST] = 1;
        $option[CURLOPT_POSTFIELDS] = $data;
    }
    if (stripos($url, 'https://') !== false) {
        $option[CURLOPT_SSL_VERIFYPEER] = false;
        $option[CURLOPT_SSL_VERIFYHOST] = false;
    }
    $ch = curl_init();
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    if (curl_errno($ch) > 0) {
        throw_exception("CURL ERROR:{$url} " . curl_error($ch));
    }
    curl_close($ch);
    return $response;
}