curl简单请求函数

作者: JONE 分类: PHPer 发布时间: 2020-08-09 00:31
 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
}