file_get_contents when url doesn't exist

file_get_contents when url doesn't exist

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling file_get_contents Failures Gracefully

When you use file_get_contents() to fetch a remote resource, PHP treats network failures as exceptions in the application flow if error reporting is strict, or returns false silently otherwise. The specific error message you encountered—failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found—indicates that the underlying cURL engine (which file_get_contents relies on when fetching URLs) received a non-2xx status code.

The challenge lies in distinguishing between a network timeout, a DNS failure, and an actual HTTP error like a 404 Not Found. If you simply wrap the call in a try-catch, you might catch ErrorException instances depending on your PHP configuration (display_errors or error_reporting), but this often feels brittle because it depends on runtime settings rather than explicit code logic.

Checking the Return Value

The most direct and reliable way to handle this is to check if file_get_contents() returns a boolean false. This happens whenever the request fails for any reason, including connection errors or HTTP error codes like 404.

Here is a robust pattern you can apply:

$contents = file_get_contents('http://somenotrealurl.com/notrealpage');

if ($contents === false) {
    // Determine if it was an HTTP error or a connection failure
    $httpCode = http_response_code();
    
    if ($httpCode !== 0) {
        // An HTTP request completed but returned an error status
        // For example, 404 Not Found, 500 Internal Server Error, etc.
        if ($httpCode === 404) {
            // Handle the "Not Found" case specifically
            $message = 'The requested page was not found.';
        } else {
            $message = sprintf('HTTP request failed with status: %d', $httpCode);
        }
    } else {
        // Connection failed, DNS error, or timeout (no HTTP header received)
        $message = 'Failed to connect to the URL or read the response.';
    }

    // Act accordingly, e.g., log the message or show a friendly UI error
    echo "Error: " . $message;
} else {
    // Success! Proceed with normal logic.
    // Note: You might still want to validate the content type or length here.
    $data = json_decode($contents, true); 
}

Why http_response_code() Matters

It is crucial to call http_response_code() immediately after the failure check. If you attempt to fetch a URL that doesn't exist, PHP's stream wrapper will not populate the global HTTP status code unless you explicitly request it or if the error handling allows it to peek at the headers before failing. However, in modern PHP versions with standard cURL streams, http_response_code() often returns 0 when the connection itself fails (e.g., DNS lookup failure).

In your specific case, where the server responded with a 404, http_response_code() will return 404. This distinction allows you to differentiate between "The server is down" and "The page doesn't exist." You can then decide whether to redirect the user, show a custom 404 page, or log a specific metric.

Alternative Approaches with cURL

If you find that checking the return value of file_get_contents() feels too implicit for your needs, consider switching to curl_init(). This approach gives you explicit control over the stream context and allows you to set error callbacks.

$ch = curl_init('http://somenotrealurl.com/notrealpage');

// Configure cURL options if necessary
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false); // Don't auto-throw errors on non-2xx codes

$response = curl_exec($ch);

if (curl_errno($ch)) {
    // Network error or timeout
    $errorNumber = curl_errno($ch);
    $errorMessage = curl_error($ch);
    echo "Network Error: $errorMessage";
} elseif (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
    // HTTP protocol error (e.g., 404, 500)
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if ($httpCode == 404) {
        echo "Page not found.";
    } else {
        echo "HTTP Error: $httpCode";
    }
} else {
    // Success
    $data = json_decode($response, true);
}

curl_close($ch);

Trade-offs and Considerations

While file_get_contents is convenient because it requires no additional dependencies or initialization, its error handling can be opaque if not carefully checked. One common pitfall is assuming that a non-200 status code always means the content is invalid JSON or HTML; sometimes valid responses come with 4xx codes intentionally (like 404s).

Another consideration is the overhead of cURL. For simple GET requests, file_get_contents is faster to write and execute. However, if you are building a high-throughput application, the explicit control offered by cURL often justifies the slightly more verbose syntax.

If you are working within the Laravel ecosystem and want to leverage its HTTP client for this purpose, you can use the built-in Http facade, which abstracts these concerns further while maintaining robust error handling capabilities. For instance, checking the response status via $response->getStatusCode() is generally cleaner than parsing global variables from stream wrappers.

Ultimately, the decision depends on your specific architectural needs. If you are dealing with external APIs or third-party endpoints where 404s are frequent and expected, explicitly checking http_response_code() after a false return from file_get_contents provides the lightweight solution you need without introducing heavy dependencies.

Our network