Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Setting a file_get_contents timeout [duplicate]

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?

like image 476
Xperplay Avatar asked Mar 30 '14 09:03

Xperplay


2 Answers

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);
?>
like image 53
Abed Hawa Avatar answered Oct 22 '22 21:10

Abed Hawa


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.

like image 45
Shankar Narayana Damodaran Avatar answered Oct 22 '22 19:10

Shankar Narayana Damodaran