PHP curl Connection timed out error

Irfan.gwb picture Irfan.gwb · Jun 13, 2018 · Viewed 10.2k times · Source

I am calling an API using curl in PHP, Sometimes it works fine and sometimes I get Failed to connect to api-domain.com port 80: Connection timed out

It's a little strange that sometimes it's working and sometimes it's not. To troubleshoot the issue I have printed the curl_getinfo() when it is not working, please check it below.

It's showing connect time = 0 and total time = 130 sec, I am not really sure what it means. If any one has good understanding about it please review the below log and help me understand what the exact issue is.

[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

Thank in advance!

Edit

Sometimes curl request comes to the REST API Server and sometimes it doesn't. It is discarded at connection level itself, does not reach to the REST API server. I am little confused as to why sometimes it connects and sometimes it doesn't.

Answer

Cid picture Cid · Jun 13, 2018

Refering to the documentation of curl_getinfo(), connect_time is the time in second it took to establish last connection and total_time is the time in second for the last transaction.

You can redefine the timeouts using curl_setopt(). In example, curl_setopt($cHandler, CURLOPT_CONNECTTIMEOUT, 42); to set 42 seconds of connection timeout or curl_setopt($cHandler, CURLOPT_CONNECTTIMEOUT, 0); for no connection timeout. The same way, curl_setopt($cHandler, CURLOPT_TIMEOUT, 42); will define 42 seconds of execution timeout.