11

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?

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
Xperplay
  • 289
  • 1
  • 3
  • 14
  • A similar question was asked here: http://stackoverflow.com/questions/10236166/does-file-get-contents-have-a-timeout-setting – Simon East Mar 16 '15 at 02:35

2 Answers2

12

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);
?>
Abed Hawa
  • 1,372
  • 7
  • 18
10

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)
)
));

Your Question....

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.

Community
  • 1
  • 1
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • 1
    thank you for the quick answer. I found this great tool for testing which might be useful for anyone reading this question. http://www.seanshadmand.com/2012/06/21/fake-response-server-slow-response-time-generator/ – Xperplay Mar 30 '14 at 09:51