I am using file_get_contents
to get a headers of an external page to determine if the external page is online like so:
$URL = "http://page.location/";
$Context = stream_context_create(array(
'http' => array(
'method' => 'GET',
)
));
file_get_contents($URL, false, $Context);
$ResponseHeaders = $http_response_header;
$header = substr($ResponseHeaders[0], 9, 3);
if($header[0] == "5" || $header[0] == "4"){
//do stuff
}
This is working well except when the page is taking too long to respond.
How do I set a timeout?
Will file_get_headers
return FALSE if it has not completed yet and will PHP move to the next line if it has not completed the file_get_contents
request?
Here is an example of how can you set the timeout for this function:
<?php
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1
)
)
);
file_get_contents("http://example.com/", 0, $ctx);
?>
Add a timeout
key inside the stream_context_array
$Context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'timeout' => 30, //<---- Here (That is in seconds)
)
));
will file_get_headers return FALSE if it has not completed yet and will PHP move to the next line if it has not completed the file_get_contents request?
Yes , it will return FALSE along with the below warning message as shown.
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With