HTTP requests with file_get_contents, getting the response code

HTTP requests with file_get_contents, getting the response code

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

Stefan Bogdanescu

Founder & Senior Architect

Decoding HTTP Responses from file_get_contents

Using file_get_contents to make HTTP requests is a common pattern in PHP, often chosen for its brevity. However, relying on it for POST requests introduces specific challenges regarding error handling and response inspection. When an upstream server rejects your request with a status like 400 Bad Request, the standard behavior of file_get_contents is to emit a warning and return false. This forces you to rely on trigger_error() or global error handlers to catch the issue, which obscures the actual HTTP status code contained within the failure message.

To suppress these warnings and programmatically access the response code, you must leverage the stream context options more deeply than simple header manipulation allows. The core mechanism involves setting the info option within the 'http' array of your context options. This tells PHP to capture detailed metadata about the request lifecycle, including the final HTTP status code returned by the server.

Here is how to implement this:

$options = array(
    'http' => array(
        'method'  => 'POST',
        'content' => $data,
        'header'  => 
            "Content-Type: text/plain\r\n" .
            "Content-Length: " . strlen($data) . "\r\n",
        'ignore_errors' => true // Suppress warnings for non-2xx responses
    )
);

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response === false) {
    // Access the response code from the info array
    $httpCode = null;
    if (isset($http_response_header)) {
        // This usually doesn't help here as headers are separate
    } else {
        // The reliable way is checking the context options result
        // But file_get_contents doesn't return the info array directly.
        // You must use stream_get_meta_data or check specific flags.
        
        // Actually, the standard way to get the code from a failed request 
        // without warnings is to parse the error message if 'ignore_errors' isn't set,
        // OR use stream_context_set_option with context options that return info.
        
        // The correct approach for getting the code from a failed request:
        $error = null;
        if (isset($context['http']['ignore_errors'])) {
            // If we ignore errors, file_get_contents still returns false on HTTP errors
            // unless we explicitly handle the response headers.
        }
        
        // To get the code reliably without a warning:
        $context = stream_context_create(array(
            'http' => array(
                'method'  => 'POST',
                'content' => $data,
                'header'  => "Content-Type: text/plain\r\n" .
                             "Content-Length: " . strlen($data) . "\r\n",
                // Critical: Set this to capture the response headers even on failure
            )
        ));
        
        $response = file_get_contents($url, false, $context);
        
        if ($response === false) {
            // The warning is suppressed by default behavior when we check $response == false?
            // No, we need to set ignore_errors to true to suppress the E_WARNING.
            $contextOptions = array(
                'http' => array(
                    'method'  => 'POST',
                    'content' => $data,
                    'header'  => "Content-Type: text/plain\r\n" .
                                 "Content-Length: " . strlen($data) . "\r\n",
                    'ignore_errors' => true 
                )
            );
            $context = stream_context_create($contextOptions);
            
            $response = file_get_contents($url, false, $context);
            
            // Even with ignore_errors, we need to extract the code.
            // The standard way is to check the last line of headers if available.
        }
    }
}

The implementation above highlights a crucial nuance: file_get_contents does not return an associative array containing the status code when using streams directly. Instead, it returns the body of the response on success and false on failure. To retrieve the HTTP status code without triggering a PHP warning, you must combine 'ignore_errors' => true with a strategy to extract the code from the stream's metadata or by parsing the headers if they were successfully retrieved before the failure logic kicked in.

A more robust pattern involves checking the http_response_header global variable after the request. If the server returned a response body (even an error body like "400 Bad Request"), PHP often populates this array. You can then parse the first line to extract the numeric code:

$response = file_get_contents($url, false, $context);

if ($response === false) {
    // Check if headers were populated despite the false return
    if (!empty($http_response_header)) {
        $headers = array_filter($http_response_header);
        $firstLine = reset($headers);
        
        // Parse "HTTP/1.1 400 Bad Request"
        $parts = explode(' ', $firstLine);
        $statusCode = isset($parts[1]) ? (int)$parts[1] : null;
        
        if ($statusCode) {
            throw new \Exception("HTTP Error: {$statusCode} - " . ltrim($firstLine, 'HTTP/'));
        }
    }
    
    // If headers are empty, it might be a network error (DNS timeout, connection refused)
    // rather than an HTTP-level response.
}

This approach allows you to throw custom exceptions while retaining the specific HTTP status code, providing clear feedback for debugging or retry logic. However, developers should be aware that file_get_contents is less suitable for modern API consumption compared to the Guzzle HTTP client or native cURL extensions. These libraries offer explicit methods like getStatusCode() and built-in exception handling (RequestException) that abstract away the stream context complexity entirely.

For projects using Laravel, consider utilizing the built-in HTTP facade or the underlying Guzzle adapter, which handles status codes and warnings gracefully without manual stream parsing. If you must stick to procedural PHP for performance or legacy reasons, understanding the ignore_errors flag and the http_response_header global is essential for building resilient code that doesn't crash silently on network issues.

Our network