1

我正在使用curl_setopt在我的請求中設置標頭。 具體而言,我想使它成爲頭部包含正在使用的授權類型。未使用curl_setopt設置標頭PHP

// Define headers to use 
    $header = array(
     'HTTP/1.1', 
     'Content-type: text/plain', 
     'Authorization: Basic ' . base64_encode("$username:$password") 
); 

// Below I prepare the request 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL,$URL); 
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);; 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // set custom header 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); 

$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code 

if (curl_errno($ch)) { 
    echo 'CURL Error: ' . curl_error($ch); 
} 

$result=curl_exec ($ch); 

echo $result; 

curl_close ($ch); 

我的使用情況下正在運行的tcpdump分析報頭(通過找到字符串「授權:基本」:當該php程序發出該請求密碼

如此如此獲得的用戶名的base64編碼到$ URL(通過加載這個程序的頁面),TCP Dump應該檢測到它發送出來的base64編碼,對吧?

但是,tcpdump沒有取出標題,我認爲這是因爲我沒有設置正確的標題

+0

要求CURLINFO_HTTP_CODE curl_exec()之前,是沒有意義的,你很可能得到垃圾數據 – hanshenrik

+0

你能檢查這段代碼返回什麼嗎?它可能會給你一些線索! $ headers = array(); $ cookies = array(); $ debugInfo =''; $ html = hhb_curl_exec2($ ch,$ url,$ headers,$ cookies,$ debugInfo); var_dump($ headers,$ cookies,$ debuginfo軟,$ HTML); https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php – hanshenrik

回答

1

您需要執行卷曲請求。

$result = curl_exec($ch); 

//remember to close the connection too 
curl_close($ch). 

如果你不叫curl_exec(),你永遠不會發送請求,因此從不送頭。

0

您設置HTTP標頭的方式是正確的。
你忘了打電話給curl_exec($ch);嗎?

1

對我來說沒問題。但是,使用CURLOPT_USERPWD時不需要授權標頭,因爲它將覆蓋任何現有的授權標頭。在標題數組中。

一個建議是通過將它發送到http://requestb.in來調試你的捲曲請求。

0

你必須先運行curl_exec:

$result=curl_exec ($ch); 

,然後檢查狀態代碼:

$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code 

if (curl_errno($ch)) { 
    echo 'CURL Error: ' . curl_error($ch); 
}