我正在尝试通过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
我尝试将内容长度标头添加到 cURL 配置中:
'Content-Length: ' . strlen($postData)
但随后 cURL 失败并显示错误 52(来自服务器的空回复(。为了确保我指定的内容长度实际上是正确的,我尝试在CURLOPT_POSTFIELDS中添加一个 cus tom 字符串(如 'foo=bar'(,并设置 Content-Length: 7,但结果是一样的。
我也试图掩盖整个代码并使用Zend 2 Http Client,但没有运气。我想我已经阅读了所有其他关于 cURL 52 错误的帖子,但它们似乎都与 Content-Length 标头没有任何共同之处,所以我希望这里有人可以帮助我。
如果您需要我的更多信息,请告诉我。
对 $action
变量中指定的 URL 的POST
请求返回 HTTP 302 重定向,其中 CURL 将使用 GET
发送下一个请求,请参阅此处的第 2 段:http://curl.haxx.se/docs/manpage.html#-L。
您已经使用 CURLOPT_CUSTOMREQUEST
来解决此问题,但它也需要CURLOPT_POSTREDIR
,如此处的字符串部分所述:http://evertpot.com/curl-redirect-requestbody/
不应显式设置Content-Length
,而应让 CURL 处理该。
或者,您可以手动"跟随"Location
标头,并在$action
变量中使用该标头中的URL(首先尝试进行测试可能会很有用(。