PHP curl 连接超时错误

PHP curl Connection timed out error

我在 PHP 中使用 curl 调用 API,有时它工作正常,有时我得到 Failed to connect to api-domain.com port 80: Connection timed out

有点奇怪,有时能用,有时不能用。要解决我打印的 curl_getinfo() 无法正常工作的问题,请在下方查看。

它显示连接时间 = 0 和总时间 = 130 秒,我不太确定这是什么意思。如果有人对此有很好的了解,请查看以下日志并帮助我了解确切的问题所在。

[url] => http://api-domain.com/?act=get_story_banners
[content_type] => text/html; charset=UTF-8
[http_code] => 200
[header_size] => 630
[req   uest_size] => 283
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 130.335916
[namelookup_time] => 0.000016
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 744
[speed_download] => 13814
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[redirect_url] => 
[primary_ip] => 34.231.133.7
[certinfo] => Array()
[primary_port] => 80
[local_ip] => xxx.xxx.xxx.xxx
[local_port] => 48080

提前致谢!

编辑

有时 curl 请求会到达 REST API 服务器,有时不会。它在连接级别本身被丢弃,不会到达 REST API 服务器。我有点困惑为什么有时它连接有时不连接。

参考curl_getinfo()的文档,connect_time是上次建立连接的时间,total_time是最后一次交易的时间,以秒为单位。

您可以使用 curl_setopt() 重新定义超时。例如,curl_setopt($cHandler, CURLOPT_CONNECTTIMEOUT, 42); 设置 42 秒的 connection 超时或 curl_setopt($cHandler, CURLOPT_CONNECTTIMEOUT, 0); 没有 connection 超时。同样,curl_setopt($cHandler, CURLOPT_TIMEOUT, 42); 将定义 42 秒的 执行 超时。

经过大约 1 周的努力并尝试了所有建议的选项后,我终于发现这既不是连接问题也不是 API api-domain.com 问题。对我来说有点奇怪,但确实是我调用 API 的服务器扩展问题,我增加了配置(RAM 和 CPU)并发现问题已解决。

希望我在这个问题上的经验能帮助别人并节省他们进行故障排除的时间。

谢谢大家的评论和建议解决方案。