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!
source share