2016-04-11 279 views
1

我試圖捲曲導致403 Forbidden錯誤的遠程站點。在同一臺服務器上,我可以通過終端運行以下兩個命令。第一次失敗,第二次失敗。如何讓我的PHP代碼與第二個終端命令相匹配?PHP cURL導致403禁止

此終端命令導致沒有任何返回。

curl http://www.barneys.com 

在一個正確的結果這個終端指令結果(網頁的HTML)

curl -L http://www.barneys.com 

我的PHP代碼:

$ch = curl_init('http://www.barneys.com'); 
$http_headers = array(
'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:40.0)' . 'Gecko/20100101 Firefox/40.0', 
'Accept: */*', 
'X-Requested-With: XMLHttpRequest', 
'Referer: http://www.barneys.com', # IMPORTANT 
'Accept-Language: pt-BR,en-US;q=0.7,en;q=0.3', 
); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_headers); 
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_REFERER, 'http://www.barneys.com'); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
$response = curl_exec($ch); 
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL); 
curl_close($ch); 

echo $response; 

編輯:下面是從日誌通過PHP的cURL請求:

* About to connect() to www.barneys.com port 80 (#0) 
* Trying 23.204.27.110... * connected 
* Connected to www.barneys.com (23.204.27.110) port 80 (#0) 
> GET/HTTP/1.1 
Host: www.barneys.com 
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:40.0)Gecko/20100101 Firefox/40.0 
Accept: */* 
X-Requested-With: XMLHttpRequest 
Referer: http://www.barneys.com 
Accept-Language: pt-BR,en-US;q=0.7,en;q=0.3 
Connection: keep-alive 

< HTTP/1.1 403 Forbidden 
< Server: AkamaiGHost 
< Mime-Version: 1.0 
< Content-Type: text/html 
< Content-Length: 265 
< Expires: Mon, 11 Apr 2016 23:22:16 GMT 
< Date: Mon, 11 Apr 2016 23:22:16 GMT 
< Connection: close 
< 
* Closing connection #0 
+0

首先狀態碼是301。基本上在curl -L狀態中遵循重定向,所以'curl_setopt($ ch,CURLOPT_FOLLOWLOCATION,true);'應該就足夠了。附上一些輸出或錯誤來調試錯誤 – georoot

+0

謝謝@georoot我已經添加了上面的日誌。讓我知道如果這有幫助! – yourfavorite

+0

似乎如果你添加一個頭,「連接:保持活着」,它會起作用。 – drew010

回答

1

您的php cURL請求中沒有包含請求標頭。爲了解決這個問題,添加以下行的設置CURLOPT_HTTPHEADER選擇權之前:

curl_setopt($ch, CURLOPT_HEADER, true); 

PHP curl docs

CURLOPT_HEADER TRUE包括在輸出中的標題。

此外,如果向URL添加尾部斜線,URL將不需要由cURL重建。很多你的代碼似乎是不必要的。這是一個修剪下來的工作示例:

<?php 
$ch = curl_init('http://www.barneys.com/'); 
$http_headers = array(
    'User-Agent: Junk', // Any User-Agent will do here 
); 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_headers); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$response = curl_exec($ch); 
curl_close($ch); 

echo $response;