Deep into PHP function file_get_contents Timeout processing method _php instance

Source: Internet
Author: User
I. Increase time limit for timeouts
Note here: Set_time_limit only sets the timeout for your PHP program, not the timeout for the file_get_contents function to read the URL. The real modification of the file_get_contents delay can be resource $context timeout parameters:
Copy Code code as follows:

$opts = Array (
' HTTP ' =>array (
' Method ' => ' get ',
' Timeout ' =>60,
)  );
$context = Stream_context_create ($opts); $html =file_get_contents (' http://www.example.com ', false, $context);

if 二、一次 has a delay, try it a few more times.
Sometimes failure is due to 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 && ($str = @file_get_contents (' http ... ')) ===false $cnt + +;
The above method of dealing with timeout is OK.
Someone has found the ' method ' => ' get ', which can also be set to post, as follows
Copy Code code as follows:

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.example.com ', $data);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.