How to Read File Content from URL with Time out in PHP?


In PHP, you can read the content via the function file_get_contents or fopen. However, by default, there is no time out setting for these two functions. So if the target URL takes long time to return the file contents, the PHP process may seem frozen. You could set a time out to these two functions so that it will return once the time limit exceeded.

The key function to use is the stream_context_create, which creates a context and stores the parameters to pass to these two functions.

file_get_contents_with_timeout

The following function returns the content of the URL with a timeout setting:

1
2
3
4
5
6
function file_get_contents_with_timeout($path, $timeout = 30) {
    $ctx = stream_context_create(array('http'=>
        array('timeout' => $timeout)  
    ));
    return file_get_contents($path, false, $ctx);
}
function file_get_contents_with_timeout($path, $timeout = 30) {
    $ctx = stream_context_create(array('http'=>
        array('timeout' => $timeout)  
    ));
    return file_get_contents($path, false, $ctx);
}
php How to Read File Content from URL with Time out in PHP? php

php

fopen_with_timeout

Similarly, you can pass the context of timeout to the fopen function, and it becomes:

1
2
3
4
5
6
function fopen_with_timeout($path, $timeout = 30) {
    $ctx = stream_context_create(array('http'=>
        array('timeout' => $timeout)  
    ));
    return fopen($path, 'rb', false, $ctx);
}
function fopen_with_timeout($path, $timeout = 30) {
    $ctx = stream_context_create(array('http'=>
        array('timeout' => $timeout)  
    ));
    return fopen($path, 'rb', false, $ctx);
}

To get the content of a URL, use something like this:

1
2
$fp = fopen_with_timeout($url, 45);
$response = stream_get_contents($fp);
$fp = fopen_with_timeout($url, 45);
$response = stream_get_contents($fp);

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
343 words
Last Post: The C++ Windows Command Line Tool to Wait and Timeout on CreateProcess
Next Post: How to Compute the Power of Arbitrary Base without Loops in C/C++?

The Permanent URL is: How to Read File Content from URL with Time out in PHP?

Leave a Reply