curl发出请求
最近写了几个使用php curl来获取数据的脚本. 在这里把几个脚本捏合到一起, 能够满足绝大部分curl请求了.
主要功能包括:
- 支持https.
- 支持 post, get, head 3中请求方式
- 支持超时检查.
- 支持访问指定ip+host的请求.
- 支持带cookie请求.
- 返回结果异常时, 返回curl_getinfo等信息方便排错.
function request($url, $mode, array $params=array(), $cookie='', $host=''){ $mode = strtoupper($mode); $timeout = 10; $userAgent = 'CODE_SAY_(.)(.)_'; $ch = curl_init(); if(substr($url, 0, 5) == 'https'){ curl_setopt($ch, CURLOPT_SSLVERSION, 3); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } # curl 执行超时 (how long to wait to receive a completely buffered output from the server) curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); # curl 连接超时(how long to wait to make a successful connection to the server before starting to buffer the output. ) curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); # 文件流的方式返回,而非直接输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); # 访问某个域名下指定$host的机器 if(!empty($host)){ $parts = explode('/', $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: '.$parts[2])); $parts[2] = $host; $url = implode('/', $parts); } curl_setopt($ch, CURLOPT_COOKIE, $cookie); if($mode=='POST'){ curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); }else if($mode == 'HEAD'){ curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); $url .= empty($params) ? '' : ((strpos($url,'?')===false?'?':'&') . http_build_query($params)); }else{ $url .= empty($params) ? '' : ((strpos($url,'?')===false?'?':'&') . http_build_query($params)); } curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); if($result === false){ $result['curl_errno'] = curl_errno($ch); $result['curl_error'] = curl_error($ch); $result['curl_getinfo'] = curl_getinfo($ch); } curl_close($ch); return $result; } /* 如果需要获得header+body, 必须使用非head请求 curl_setopt($ch, CURLOPT_HEADER, true); $info = curl_getinfo($ch); $result['header'] = substr($tmp, 0, $info['header_size']); $result['body'] = substr($tmp, -$info['download_content_length']); */
CURLOPT_TIMEOUT: how long to wait to receive a completely buffered output from the server
CURLOPT_CONNECTTIMEOUT: how long to wait to make a successful connection to the server before starting to buffer the output.
以下载一个mp3文件为例:connecttimeout是指由请求发出开始到收到请求头的第一个字符;timeout是指请求发出开始到完整接收整个mp3文件的时间。
代码添加了一个功能:指定参数host,按照ip来访问http服务器。