PHP给cURL函数设置头信息

时间:2017-07-28
本文章向大家介绍PHP给cURL函数设置头信息,需要的朋友可以参考一下。

我想知道是否/如何在PHP中为cURL HTTP请求添加自定义标头。我试图模仿iTunes如何抓取艺术作品并使用这些非标准标题:

具体方法如下:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

实例:

/**
 * 
 * @param string $url
 * @param string|array $post_fields
 * @param array $headers
 * @return type
 */
function cUrlGetData($url, $post_fields = null, $headers = null) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($post_fields && !empty($post_fields)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    }
    if ($headers && !empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);
    return $data;
}

用法示例:

$url = "http://www.myurl.com";
$post_fields = 'postvars=val1&postvars2=val2';
$headers = ['Content-Type' => 'application/x-www-form-urlencoded', 'charset' => 'utf-8'];
$dat = cUrlGetData($url, $post_fields, $headers);