PHP有着很好的curl机制,但是用起来总是不那么的令人满意,因为它需要好几步的操作和,好多难记的参数,这里我将php的curl封装了一下,使它不那么的复杂。

<?php
/**
 * php模拟curl请求
 *
 * @param string $url     请求的url
 * @param string $method  请求的方法, 默认POST
 * @param array  $data    请求传递的数据
 * @param array  $header  请求设置的头信息
 * @param int    $head    是否打印头信息
 * @param int    $body    是否打印body信息
 * @param int    $timeout 设置超时时间
 *
 * @return array
 */
function curl($url,$method="POST",$data=array(),$header=array(),$head=0,$body=0,$timeout = 30)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if (strpos($url, "https") !== false ) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        }
    }
    if (!empty($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    switch ($method) {
    case 'POST':
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        break;
    case 'GET':
        break;
    case 'PUT':
        curl_setopt($ch, CURLOPT_PUT, 1);
        curl_setopt($ch, CURLOPT_INFILE, '');
        curl_setopt($ch, CURLOPT_INFILESIZE, 10);
        break;
    case 'DELETE':
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        break;
    default:
        break;
    }
 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, $head);
    curl_setopt($ch, CURLOPT_NOBODY, $body);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rtn = curl_exec($ch); //获得返回
    if (curl_errno($ch)) {
        echo 'Errno'.curl_error($ch);//捕抓异常
    }
    curl_close($ch);
    return $rtn;
}
?>