2011-11-13 57 views
234

我想知道是否/如何將自定義標題添加到PHP中的cURL HTTP請求。我試圖效仿iTunes抓取藝術品的方式,並使用這些非標準標題:PHP cURL自定義標題

X-Apple-Tz: 0 
X-Apple-Store-Front: 143444,12 

我該如何將這些標題添加到請求中?

回答

116

使用以下語法

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/process.php"); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

$headers = [ 
    'X-Apple-Tz: 0', 
    'X-Apple-Store-Front: 143444,12', 
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 
    'Accept-Encoding: gzip, deflate', 
    'Accept-Language: en-US,en;q=0.5', 
    'Cache-Control: no-cache', 
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8', 
    'Host: www.example.com', 
    'Referer: http://www.example.com/index.php', //Your referrer address 
    'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0', 
    'X-MicrosoftAjax: Delta=true' 
]; 

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

$server_output = curl_exec ($ch); 

curl_close ($ch); 

print $server_output ; 
+15

你也值得一個cookie – SebastianView

+2

欺騙用戶代理字符串聽起來對我來說是一個壞主意。 [這是HTTP規範說的](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43)。 – starbeamrainbowlabs

+1

@SebastianView你得到一個餅乾!你得到一個餅乾!你得到一個餅乾!每個人都有一個餅乾! – Dheeraj

0

這是一個基本的功能:

/** 
* 
* @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);