Home >Backend Development >PHP Tutorial >How to Configure Timeouts in `file_get_contents()` for Looping Through Links?

How to Configure Timeouts in `file_get_contents()` for Looping Through Links?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 19:05:10540browse

How to Configure Timeouts in `file_get_contents()` for Looping Through Links?

Timeout Settings in file_get_contents()

When utilizing file_get_contents() within a loop to retrieve content from multiple links, it's crucial to consider potential timeouts.

File_get_contents() Timeout Period:

Yes, file_get_contents() does have a default timeout period defined by the default_socket_timeout ini-setting, which is set to 60 seconds (1 minute). This means that if a connection to a remote resource takes longer than 60 seconds to establish, file_get_contents() will time out.

Customizing Timeout:

To override the default timeout, you can use the following methods:

  • ini_set(): Adjust the default_socket_timeout setting on the fly. For example, to set a 15-minute timeout:
ini_set('default_socket_timeout', 900); // 900 Seconds = 15 Minutes
  • stream_context_create(): Create an HTTP context and specify the timeout as HTTP context options:
$ctx = stream_context_create(array('http' =>
    array(
        'timeout' => 1200,  //1200 Seconds is 20 Minutes
    )
));

echo file_get_contents('http://example.com/', false, $ctx);

By setting a custom timeout, you can ensure that file_get_contents() waits for a specified period before timing out. This gives you greater control over the behavior of your script and prevents it from moving on to the next link prematurely.

The above is the detailed content of How to Configure Timeouts in `file_get_contents()` for Looping Through Links?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn