PHP Timeout Prevention

I am working on a PHP script that calls an API call to an external site. However, if this site is unavailable or the request timeout, I would like my function to return false.

I found the following, but I'm not sure how to implement it on my script, since I use "file_get_contents" to extract the contents of an external file call.

Limit the execution time of a function or PHP command

$fp = fsockopen("www.example.com", 80); if (!$fp) { echo "Unable to open\n"; } else { fwrite($fp, "GET / HTTP/1.0\r\n\r\n"); stream_set_timeout($fp, 2); $res = fread($fp, 2000); $info = stream_get_meta_data($fp); fclose($fp); if ($info['timed_out']) { echo 'Connection timed out!'; } else { echo $res; } } 

(From: http://php.net/manual/en/function.stream-set-timeout.php )

How would you address such a problem? Thanks!

+4
source share
4 answers
 <?php $fp = fsockopen("www.example.com", 80); if (!$fp) { echo "Unable to open\n"; } else { stream_set_timeout($fp, 2); // STREAM RESOURCE, NUMBER OF SECONDS TILL TIMEOUT // GET YOUR FILE CONTENTS } ?> 
0
source

I would recommend using the cURL family of PHP functions. Then you can set the timeout using curl_setopt() :

 curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2); // two second timeout 

This will cause the curl_exec() function to return FALSE after the timeout.

In general, using cURL is better than any file reading function; it is more reliable, has more features and is not considered a security risk. Many system administrators disable reading of deleted files, so using cURL will make your code more portable and safe.

+1
source

From the PHP manual for File_Get_Contents (comments):

 <?php $ctx = stream_context_create(array( 'http' => array( 'timeout' => 1 ) ) ); file_get_contents("http://example.com/", 0, $ctx); ?> 
0
source
 <?php $fp = fsockopen("www.example.com", 80, $errno, $errstr, 4); if ($fp) { stream_set_timeout($fp, 2); } 
0
source

All Articles