[英]PHP cURL returns error 52 if Content-Length is set
我正在嘗試通過php cURL在遠程網站中發布表單。
這是我的cURL配置(我在注釋中添加了一些解釋):
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $action);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); //without this line the request is being sent with GET method (I can see that with curl_getinfo)
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); //$postData is an urlencoded string
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36');
curl_setopt($ch, CURLOPT_REFERER,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding: gzip, deflate',
'Accept-Language: en-US,en;q=0.8',
'Expect:',
'Content-Type: application/x-www-form-urlencoded',
'Connection: keep-alive',
'Cache-Control: max-age=0',
'Origin: http://XXX',
));
執行這樣的配置后,我收到這樣的響應:
string(610) "HTTP/1.1 302 Found
Location: http://XXX
Vary: Accept-Encoding
Content-type: text/html; charset=utf-8
Server: DWS
Content-Length: 15536
Accept-Ranges: bytes
Date: Wed, 17 Dec 2014 10:59:35 GMT
X-Varnish: 2567206754
Age: 0
Via: 1.1 varnish
Connection: keep-alive
HTTP/1.1 411 Length Required
Content-Type: text/html
Server: DWS
Content-Length: 357
Accept-Ranges: bytes
Date: Wed, 17 Dec 2014 10:59:35 GMT
X-Varnish: 2567207187
Age: 0
Via: 1.1 varnish
Connection: keep-alive
我試圖將Content-Length標頭添加到cURL配置:
'Content-Length: ' . strlen($postData)
但是,然后cURL失敗,並顯示錯誤52(來自服務器的空答復)。 為了確保我指定的內容長度實際上是正確的,我嘗試向CURLOPT_POSTFIELDS(如'foo = bar')添加一個自定義字符串,並設置Content-Length:7,但結果是相同。
我也嘗試隱蔽整個代碼並使用Zend 2 Http Client,但是沒有運氣。 我想我已經閱讀了所有其他有關cURL 52錯誤的文章,但是它們似乎都與Content-Length標頭沒有共同之處,因此我希望這里的人能對我有所幫助。
如果您需要我提供的更多信息,請告訴我。
對$action
變量中指定的URL的POST
請求返回HTTP 302重定向,其中CURL將使用GET
發送下一個請求,請參見此處的第二段: http : //curl.haxx.se/docs/manpage.html #-L
您已經使用CURLOPT_CUSTOMREQUEST
來解決此問題,但是它也需要CURLOPT_POSTREDIR
,如“ 字符串”部分中的記錄: http : //evertpot.com/curl-redirect-requestbody/
您不應顯式設置Content-Length
而應由CURL處理。
或者,您可以手動“跟隨” Location
標頭,並在$action
變量中使用該標頭中的URL(嘗試先進行測試可能很有用)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.