You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP禁用cURL时,如何获取400状态请求的响应体?

Fixing file_get_contents() to Retrieve 400 Status Response Bodies in PHP

Ah, I’ve dealt with this exact frustration before! The default behavior of file_get_contents() is to throw out the response body whenever it encounters an HTTP error status code (like 400 Bad Request), which is why you can only grab the headers via $http_response_header but not the actual body. Luckily, there’s a straightforward workaround using PHP’s stream contexts.

The Solution: Enable ignore_errors in the Stream Context

You just need to create a custom stream context that tells PHP to ignore HTTP error statuses and return the response body regardless. Here’s a complete example:

// Create a stream context with error handling disabled
$context = stream_context_create([
    'http' => [
        'ignore_errors' => true, // This is the critical setting
        // Add any additional headers your request needs
        'header' => [
            'Content-Type: application/json',
            'Accept: application/json'
        ]
    ]
]);

// Your target API endpoint
$apiUrl = 'https://your-target-api.com/endpoint';

// Fetch the response (including body for 400 statuses now!)
$responseBody = file_get_contents($apiUrl, false, $context);

// Verify the response body
var_dump($responseBody);

// Optional: Extract the status code from $http_response_header
$statusCode = null;
foreach ($http_response_header as $headerLine) {
    // Check for the HTTP status line (works for HTTP/1.x and HTTP/2)
    if (preg_match('/^HTTP\/\d+\.\d+\s+(\d+)/', $headerLine, $matches)) {
        $statusCode = (int)$matches[1];
        break;
    }
}

echo "HTTP Status Code: " . $statusCode;

Key Notes:

  • ignore_errors: This flag overrides PHP’s default behavior of treating non-2xx statuses as failures, ensuring the response body is returned even for 400, 404, 500, etc.
  • Handling POST Requests: If you need to send a POST request, add the method and content parameters to the stream context:
    $context = stream_context_create([
        'http' => [
            'ignore_errors' => true,
            'method' => 'POST',
            'header' => 'Content-Type: application/x-www-form-urlencoded',
            'content' => http_build_query(['key' => 'value', 'another_key' => 'another_value'])
        ]
    ]);
    
  • Legacy PHP Versions: If you’re using PHP < 8.0, avoid str_starts_with() and use the regex check or substr($headerLine, 0, 5) === 'HTTP/' to detect the status line.

This approach keeps you within the constraints of not using cURL and lets you access the full response data for any HTTP status code.

内容的提问来源于stack exchange,提问作者Samul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:19:36