Details the timeout of PHP built in access resources time_out file_get_contents read_file

  • 2020-06-07 04:04:12
  • OfStack

Ask questions
I loop file_get_contents to grab a heap of url, but always stop before the 100th URL, prompting me: "Warning: file_get_contents(URL) [function.file-ES13en -
contents]: failed to open stream: HTTP request failed! HTTP/1.0 500 Read timed out
in D:\website\extra.php on line 65"
I have set_time_limit(0) at the beginning of the program; Well, what could be the reason for the mistake?
answer
set_time_limit simply sets the timeout of your PHP program, not the file_get_contents function that reads the timeout of URL.
From the warning message, it appears that there is a server 500 error on the crawled web page. It may be that his program has timed out.
To change the timeout of file_get_contents, use the timeout parameter of resource $context:

$opts = array(
'http'=>array(
    'method'=>"GET",
    'timeout'=>60,
   )
);
$context = stream_context_create($opts);
$html =file_get_contents('http://www.example.com', false, $context);
fpassthru($fp);

The readfile function timeout is set to 10 seconds, and if you are careful, there are a few other configurations in the array. http in the first dimension is the network protocol specified, and method in the second dimension is get,post,head, etc. timeout is the timeout. I think many people use the built-in file_get_contents function of php to download web pages because it's simple enough to use. Many people use it simply by passing in a link that automatically sends get requests and downloads the content. If the situation is more complicated, such as using POST requests, using proxy downloads, defining ES63en-ES64en, etc., then many people will think that this function cannot do such a thing and will choose another way, such as curl. In fact, these things can also be done with file_get_contents,
It is through its third argument that the context requested by http is set.
Support to set up and use way to see the official explanation: http: / / www php. net manual/en/context http. php
Attached: now I know that support context parameters php file_get_contents built-in functions, file_put_contents, readfile, file, fopen, copy (estimated the function of 1 class support, TBC).

function Post($url, $post = null)
{
$context = array();
if (is_array($post))
{
ksort($post);
$context['http'] = array
(
'timeout'=>60,
'method' => 'POST',
'content' => http_build_query($post, '', '&'),
);
}
return file_get_contents($url, false, stream_context_create($context));
}
$data = array
(
'name' => 'test',
'email' => 'test@gmail.com',
'submit' => 'submit',
);
echo Post('http://www.yifu.info', $data);

OK, the above function is perfect for both timeout control and Post value passing. With the improved RC4 encryption and decryption algorithm of Kangsheng, it is much simpler to do a high security webservice.

Related articles: