简体   繁体   English

重定向中的PHP cURL超时

[英]PHP cURL timeout in redirections

I was testing the 303 redirection in PHP for a use case in one of my company websites and I noticed a huge delay between 2 different cases, one execution was normal and the other lasted 10 seconds, I realized that was the timeout I set (with the CURLOPT_TIMEOUT flag). 我在一个公司网站上针对一个用例在PHP中测试了303重定向,但我注意到2个不同用例之间存在巨大的延迟,一个执行正常,而另一个持续10秒,我意识到这是我设置的超时时间( CURLOPT_TIMEOUT标志)。

The test was to try the case where a POST query transforms into a GET query after a redirection. 测试是尝试在重定向后将POST查询转换为GET查询的情况。

I tested it with 301 and 302 redirections also and the result was the same. 我也使用301和302重定向对其进行了测试,结果是相同的。 Finally after struggling a lot with this issue I found the solution and I thought it'd be interesting to share. 最后,在为这个问题苦苦挣扎之后,我找到了解决方案,并且我认为分享它会很有趣。

Redirect page 重定向页面

<?php

header("HTTP/1.1 303 See Other");    
header("Location: http://127.0.0.1/test-303-redirection-2.html");

cURL example script cURL示例脚本

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1/test-303-redirection-1.php");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "field1=value1&field2=value2");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'host: 127.0.0.1',
    'accept: */*',
    'content-length: 29',
    'content-type: application/x-www-form-urlencoded'
    )
);

$theResponse  = curl_exec($ch);

print_r(curl_getinfo($ch)) ;

This script lasted 10 seconds every time it was executed. 每次执行时,该脚本持续10秒。

The bug was in our cURL wrapper class, it add the content-length header using the POST fields length. 该错误位于我们的cURL包装器类中,它使用POST字段的长度添加了content-length标头。 That made headers were sent like this: 这样就使标题发送如下:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'host: 127.0.0.1',
    'accept: */*',
    'content-length: 29',
    'content-type: application/x-www-form-urlencoded'
    )
);

Just removing the content-length header from the array removed the timeout and the execution was smooth as it should be. 只需从数组中删除content-length标头,就可以消除超时,执行过程也应该顺利。 I hope this helps someone 我希望这可以帮助别人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM