php curl使用方法

/**
* 使用curl进行连接
*
* @access private
* @param string $url 远程服务器的URL
* @param string $params 查询参数,形如bar=foo&foo=bar
* @param string $method 请求方式,是POST还是GET
* @param array $my_header 用户要发送的头部信息,为一维关联数组,形如array('a'=>'aa',...)
* @return array 成功返回一维关联数组,形如array('header'=>'bar', 'body'=>'foo'),
* 失败返回false。
/
function use_curl($url, $params, $method, $my_header)
{
/
开始一个新会话 */
$curl_session = curl_init();

    /* 基本设置 */
    curl_setopt($curl_session, CURLOPT_FORBID_REUSE, true); // 处理完后,关闭连接,释放资源
    curl_setopt($curl_session, CURLOPT_HEADER, true);//结果中包含头部信息
    curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);//把结果返回,而非直接输出
    curl_setopt($curl_session, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);//采用1.0版的HTTP协议

    $header = array();

    if ($method === 'GET')
    {
        curl_setopt($curl_session, CURLOPT_HTTPGET, true);
        $url .= $params ? '?' . $params : '';
    }
    else
    {
        curl_setopt($curl_session, CURLOPT_POST, true);
        $header[] = 'Content-Type: application/x-www-form-urlencoded';
        $header[] = 'Content-Length: ' . strlen($params);
        curl_setopt($curl_session, CURLOPT_POSTFIELDS, $params);
    }

    /* 设置请求地址 */
    curl_setopt($curl_session, CURLOPT_URL, $url);

    /* 设置头部信息 */
    curl_setopt($curl_session, CURLOPT_HTTPHEADER, $header);

    curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($curl_session, CURLOPT_TIMEOUT, 5);
    
    /* 发送请求 */
    $http_response = curl_exec($curl_session);

    if (curl_errno($curl_session) != 0)
    {   
        return false;
    }

    $separator = '/\r\n\r\n|\n\n|\r\r/';
    list($http_header, $http_body) = preg_split($separator, $http_response, 2);

    $http_response = array('header' => $http_header,//肯定有值
                           'body'   => $http_body); //可能为空

    curl_close($curl_session);

    return $http_response;
}

posted on 2014-12-20 10:26  郑峰  阅读(158)  评论(0编辑  收藏  举报

导航