'file_get_contents - Connection timed out
<?php
$a = file_get_contents('http://www.google.com');
echo $
Why is the browser returning this error?
Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: Connection timed out in /home/test.php on line 2
Solution 1:[1]
Mostly probably your server cannot connect to an external resource, for example, because of firewall restrictions.
Solution 2:[2]
file_get_contents does not work well at all with getting remote files and should not be used. It does not deal with slow network connections or redirects, and does not return error codes. You should use curl instead to fetch remote files.
There is an example in the manual for curl_exec: http://us3.php.net/manual/en/function.curl-exec.php
Solution 3:[3]
I had the same problem, couldn't download using file_get_contents(), but using curl on the command line for the same URL worked fine. Turned out it tried to connect over IPv6 which failed.
I solved it by disabling IPv6 in my kernel parameters.
Solution 4:[4]
It might be server side issue, might be your server cannot communicate with other server remotely. You have to communicate with server administrator.
Solution 5:[5]
For some reason file_get_contents() fails intermittently on some websites that support IPv6 (maybe 20% of the time, the command times-out). Although disabling IPv6 resolves the issue, that is not the best solution as more sites move to IPv6.
I wrote a simple PHP gethtml() function that works around the issue using wget. This will automatically use IPv6 when IPv4 is not available. A minor drawback is that it uses an external command, but I think it is preferable to disabling IPv6.
If wget is not already installed on your distribution, you can install it as follows:
sudo apt install wget
PHP Function Example:
$myhtml = gethtml("http://example.com");
//use instead of file_get_contents() due to inconsistent IPv6 performance
function gethtml($url){return shell_exec("wget --prefer-family=IPv4 -qO- ".$url);}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hamish |
| Solution 2 | Boaz |
| Solution 3 | pfrenssen |
| Solution 4 | Mahedi Hasan |
| Solution 5 | Ken H |
