PHP - Setting a file_get_contents timeout [duplicate]

落花浮王杯 提交于 2019-12-08 16:38: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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/22742207/php-setting-a-file-get-contents-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!