Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

file_get_contents() fails with HTTP/1.1 400 Bad Request

ErrorHTTP/1.1 400 Bad Request

Short answer

A 400 means the server rejected the request itself. Read the response body first: set ignore_errors in a stream context and print $http_response_header. Then check three things: unencoded characters in the URL, a missing User-Agent or Content-Type header, and a POST that never set method and content in the context.

  • Applies to PHP 8.2, PHP 8.3, PHP 8.4
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    By default PHP discards the body of an error response. Turn on ignore_errors so you can read what the server says, and print the status line.

    $ctx = stream_context_create(['http' => ['ignore_errors' => true]]);
    $body = file_get_contents($url, false, $ctx);
    echo $http_response_header[0], PHP_EOL, $body;
  2. 2Match what you see, then jump to its fix

    1. 1The body or status line complains about the URL or query, and the URL holds spaces, accents or a raw JSON stringThe URL contains characters that are not encodedFix
    2. 2The body says a User-Agent or Content-Type is missing, or the same URL works in a browserThe server requires headers PHP did not sendFix
    3. 3The server says the body is missing or the JSON is empty, on an endpoint that expects POSTA POST was written as a plain GETFix

What does the error look like?

  • HTTP/1.1 400 Bad Request
  • file_get_contents() returns false

Cause 1 of 3

The URL contains characters that are not encoded

1Check

Print the final URL and look for spaces or special characters in the query part.

var_dump($url);

2Fix

Build the query string with http_build_query() and encode path parts before concatenating.

$url = 'https://api.example.com/search?' . http_build_query(['q' => 'red shoes', 'page' => 2]);
$body = file_get_contents($url);

3Verify

Print the status line again; it should start with HTTP/1.1 200.

file_get_contents($url);
echo $http_response_header[0];

Confirmed by php.net

Did this fix it?

Cause 2 of 3

The server requires headers PHP did not send

1Check

Compare what PHP sends with what the API documents. The User-Agent PHP sends comes from the user_agent ini setting, so check what yours holds.

php -r 'var_dump(ini_get("user_agent"));'

2Fix

Set the headers in the http context. The user_agent option is used only when the header list does not already contain a User-Agent.

$ctx = stream_context_create(['http' => [
    'header' => "Accept: application/json\r\nAuthorization: Bearer $token",
    'user_agent' => 'my-app/1.0',
]]);
$body = file_get_contents($url, false, $ctx);

3Verify

The status line changes from 400 to 200.

echo $http_response_header[0];

Confirmed by php.net

Did this fix it?

Cause 3 of 3

A POST was written as a plain GET

1Check

file_get_contents() sends GET unless the context sets method. A body only goes out when content is set, and it should match the Content-Type.

grep -n "'method'" -r src/

2Fix

Set method, header and content together.

$ctx = stream_context_create(['http' => [
    'method'  => 'POST',
    'header'  => "Content-Type: application/json\r\n",
    'content' => json_encode(['name' => 'test']),
]]);
$body = file_get_contents($url, false, $ctx);

3Verify

Print the status line and body again.

echo $http_response_header[0], PHP_EOL, $body;

Confirmed by php.net

Did this fix it?

How do I stop it coming back?

  • Always compare the result with === false and log the status line from $http_response_header.
  • Use http_build_query() for every query string.
  • Set an explicit User-Agent for every API your code calls.
  • Reach for cURL or an HTTP client when you need retries, timeouts or complex bodies.

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

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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.