Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP cURL - limit execution time

we are working with webservices but sometimes, they don't respond, they are too long to respond.

How to stop cURL if it takes more than 1 second ?

I tried :

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);

I Also tried to create a "temporary page" between my server and the webservice : my server calls a temporary page with :

set_time_limit(1);
ini_set('max_execution_time', 1);

And this temporary page calls the webservice itself with curl, but still nothing. If my webservice has a time execution of 10 seconds, i'll have to wait 10 seconds.

Any ideas ?

like image 982
d3cima Avatar asked Nov 05 '25 09:11

d3cima


1 Answers

There is a best solution.

Setting Curl's Timeout in PHP

See documentation: http://www.php.net/manual/en/function.curl-setopt.php

CURLOPT_CONNECTTIMEOUT - The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
CURLOPT_TIMEOUT - The maximum number of seconds to allow cURL functions to execute.
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds

Also don't forget to enlarge time execution of php script self:

set_time_limit(0); // to infinity for example


like image 69
Liang Rongze Avatar answered Nov 08 '25 11:11

Liang Rongze