【问题标题】:PHP cURL returns error 52 if Content-Length is set如果设置了 Content-Length,PHP cURL 返回错误 52
【发布时间】:2014-12-17 11:10:04
【问题描述】:

我正在尝试通过 php cURL 在远程网站中发布表单。

这是我的 cURL 配置(我在 cmets 中添加了几个解释):

$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 标头:

'Content-Length: ' . strlen($postData)

但随后 cURL 失败并出现错误 52(来自服务器的空回复)。 为了确保我指定的内容长度实际上是正确的,我尝试将自定义字符串添加到 CURLOPT_POSTFIELDS(如 'foo=bar'),并设置 Content-Length: 7,但结果是一样。

我还尝试隐藏整个代码并使用 Zend 2 Http Client,但没有成功。 我想我已经阅读了有关 cURL 52 错误的所有其他帖子,但似乎没有一个与 Content-Length 标头有任何共同之处,所以我希望这里有人可以帮助我。

如果您需要我的更多信息,请告诉我。

【问题讨论】:

    标签: php curl content-length


    【解决方案1】:

    POST$action 变量中指定的 URL 的请求返回一个 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(首先尝试进行测试可能很有用)。

    【讨论】:

    • 感谢您的回答,它成功了!我仍然无法实现我的目标,但我认为它与此线程无关
    猜你喜欢
    • 2016-09-30
    • 2017-02-12
    • 2020-09-30
    • 2013-11-07
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多