function: Stream_context_create, file_get_content
Creates and returns a text stream and applies a variety of options that can be used for time-out settings, proxy servers, request methods, and header information settings for processes such as fopen (), file_get_contents ().
Function Prototypes: Resource stream_context_create ([array $options [, array $params]])
When using the File_get_contents function, there is often a time-out situation, here to look at the error, to see what kind of error, the more common is the read timeout, this situation can be avoided or resolved by some means. Here is a brief introduction to two types:
Note: Set_time_limit just sets the time-out for your PHP program, not the File_get_contents function to read the URL timeout. At first thought Set_time_limit also can affect File_get_contents, later tested, is invalid. The real modification file_get_contents delay can be used with the timeout parameter of the resource $context:
One, PHP code timeout to end execution
General Code:
$opts =Array ('http'=Array ('Method'="GET", 'Timeout'= -, ));//Create a data flow context$context =stream_context_create ($opts); $html=file_get_contents ('Http://blog.sina.com/mirze',false, $context);
If you have an error, you can use the @ suppress error, such as: @file_get_contents
Example: Method can use POS and get
function Ip_taobao ($ip) {$opt= [ 'http'=[ 'Method'='Post', 'Timeout'=2 ] ]; $context=stream_context_create ($opt); $urlTaobao='http://ip.taobao.com/service/getIpInfo.php?ip='. $ip; $json= @file_get_contents ($urlTaobao,false, $context); $jsonDecode=Json_decode ($json); if($jsonDecode) {$data ['Country'] = $jsonDecode->data->Country; $data ['Province'] = $jsonDecode->data->Region ; $data [' City'] = $jsonDecode->data->City ; $data ['ISP'] = $jsonDecode->data->ISP; }Else{$data ['Country'] ='Network is disconnected'; } return$data;}
Second, the PHP code timeout, send the request again
Sometimes the failure is caused by the network and other factors, there is no solution, but can modify the program, failed to retry several times, still fail to give up, because file_get_contents () if the failure will return FALSE, so you can write the following code:
$cnt = 0;
while ($cnt < 3 && ([email protected]_get_contents (' Http://blog.sina.com/mirze ')) ===false) $cnt + +;
PHP script time-out end execution code