curl简单请求函数

111次阅读
没有评论
function get($url, $referer='', $cookie='')
{$header = array();
    $header[] = 'Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*';
    $header[] = 'Connection: Keep-Alive';
    $header[] = 'Accept-Language: zh-cn';
    $header[] = 'Cache-Control: no-cache';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Mobile/9B176 MicroMessenger/4.3.2');
    curl_setopt($ch, CURLOPT_REFERER, $referer);
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $result = curl_exec($ch);
    if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') {$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); // 获取 header 长度
        $bodyInfo = substr($result, $headerSize); // 截取掉 header
    }else{$bodyInfo = '';}
    curl_close($ch);
    return $bodyInfo;
}

去除 curl 请求结果中的 header 信息,保留 body 信息

方法一

$result = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200') {$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE); // 获取 header 长度
    $bodyInfo = substr($result, $headerSize); // 截取掉 header
}

方法二

$result = curl_exec($curl);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) == '200') {list($header, $body) = explode("\r\n\r\n", result, 2); // 通过两个回车换行来分割 header 和 body
}
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码