file_get_contents() fails with HTTP/1.1 400 Bad Request
HTTP/1.1 400 Bad RequestShort 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.
Fix it fast
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;2Match what you see, then jump to its fix
- 1
The 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
The 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
The server says the body is missing or the JSON is empty, on an endpoint that expects POSTA POST was written as a plain GETFix
- 1
What does the error look like?
HTTP/1.1 400 Bad Requestfile_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
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
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
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
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 fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix