How to handle file_get_contents when the URL or file does not exist
Warning: file_get_contents(https://example.com/missing): Failed to open stream: HTTP request failed! HTTP/1.1 404 Not FoundShort answer
When the target cannot be read, file_get_contents() returns false and raises an E_WARNING. Compare the result with === false, read the status line from the response headers to tell a 404 from a network failure, and check local paths with is_file() before reading.
Fix it fast
1Find out which cause you have
Run the call once on its own and dump the result together with the response headers. A status line means the server answered. No headers means the connection never happened or the path is local.
$r = @file_get_contents('https://example.com/missing'); var_dump($r, $http_response_header ?? null);2Match what you see, then jump to its fix
- 1
The warning ends in HTTP/1.1 404 Not Found, and the page opens with that status in a browserThe server answered with an error status such as 404Fix - 2
The call returns false and $http_response_header is not setThe host could not be reached, so there is no response at allFix - 3
Failed to open stream on a path, with no http:// or https:// in itA local file path does not existFix
- 1
What does the error look like?
Warning: file_get_contents(https://example.com/missing): Failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
Cause 1 of 3
The server answered with an error status such as 404
1Check
By default the HTTP wrapper treats error statuses as failure: the call returns false even though the server sent a body. The status line is index 0 of $http_response_header, which PHP creates in the local scope of the function that made the request.
$r = @file_get_contents($url);
echo $http_response_header[0] ?? 'no response';2Fix
Test the result with ===, and read the status line when you need to tell a missing page from other failures. Set ignore_errors to true in an http stream context if you want the body of an error response too.
$ctx = stream_context_create(['http' => ['ignore_errors' => true, 'timeout' => 10]]);
$body = file_get_contents($url, false, $ctx);
if ($body === false) {
// no HTTP response at all
} elseif (preg_match('#HTTP/\S+\s+(\d{3})#', $http_response_header[0], $m) && (int)$m[1] === 404) {
// page does not exist
}3Verify
Call it with a URL that returns 404. No warning is printed and your branch for 404 runs.
php -r '$c=stream_context_create(["http"=>["ignore_errors"=>true]]); file_get_contents("https://example.com/missing", false, $c); echo $http_response_header[0];'Confirmed by php.net
Cause 2 of 3
The host could not be reached, so there is no response at all
1Check
The headers variable is only filled when the HTTP wrapper got a response. A wrong host name or a closed port leaves it undefined.
var_dump(isset($http_response_header));2Fix
Treat false with no headers as a network failure. Set a timeout in the context so a dead host does not hold the request for the default read timeout, which comes from default_socket_timeout.
$ctx = stream_context_create(['http' => ['timeout' => 5]]);
$body = @file_get_contents($url, false, $ctx);
if ($body === false && !isset($http_response_header)) {
// network failure: log it and use a fallback
}3Verify
Point the call at a host that does not exist. It returns false quickly and your fallback runs.
php -r 'var_dump(@file_get_contents("http://no-such-host.invalid"));'Confirmed by php.net
Cause 3 of 3
A local file path does not exist
1Check
The manual says an E_WARNING is raised if the file cannot be found. Test the path before you read it.
var_dump(is_file($path), getcwd());2Fix
Build the path from __DIR__ and test it first, then compare the result with === false.
$path = __DIR__ . '/data/config.json';
$data = is_file($path) ? file_get_contents($path) : false;
if ($data === false) {
// missing or unreadable
}3Verify
Run the script from another folder. The path still resolves.
cd / && php /var/www/app/script.phpConfirmed by php.net
How do I stop it coming back?
- Always compare the result with === false, as the manual advises.
- Set a timeout in the http context for every outbound call.
- Wrap the call in one small function that returns a clear result for 404, network failure and success.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
file_get_contents() gets HTTP 403 Forbidden from a URL
the same URL opens fine in the browser
The server answered 403 to a request PHP built itself.
2 causes, each with a fixBack end
PHP cannot turn a hostname into an IP address
Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed
This warning means the operating system could not resolve the hostname PHP was asked to connect to.
3 causes, each with a fixBack end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
Apache returns 403 when a URL contains %3F
a request like /page%3Fname=test is refused while /page?name=test works
Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.
2 causes, each with a fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fix