PHP cURL gets 400 Bad Request because the URL contains a space
400 Bad RequestShort answer
A request line cannot contain a space, and a server may answer such a request with 400 Bad Request. libcurl wants a URL that is already encoded. Encode each path segment with rawurlencode(), build the query string with http_build_query(), and trim stray whitespace before the URL reaches CURLOPT_URL.
Fix it fast
1Find out which cause you have
Print the exact URL that goes into cURL. var_dump shows its length, and the second value is 1 when the URL holds a space, tab or line break anywhere.
<?php var_dump($url, preg_match('/\s/', $url));2Match what you see, then jump to its fix
- 1
The URL has a file or folder name with a space in it, such as /files/my report.pdfA path segment holds a spaceFix - 2
The URL was built with string concatenation, such as '?q=' . $text, and the text has spacesA query-string value holds a spaceFix - 3
preg_match returns 1 for a URL that looks fine when you print itWhitespace at the start or end of the URL came from its sourceFix
- 1
What does the error look like?
400 Bad RequestThe URL passed to CURLOPT_URL contains a space, for example /files/my report.pdf
Cause 1 of 3
A path segment holds a space
1Check
HTTP's request line is the method, one space, the target and one space, then the version, and the standard says no whitespace is allowed in the target. A recipient that gets an invalid request line should answer 400. libcurl's URL option must be given in URL-encoded form.
<?php
echo $url, "\n";2Fix
Encode every segment of the path with rawurlencode(), then join them with slashes. Do not run the whole path or the whole URL through rawurlencode(): it also encodes the slashes, and in a full URL the colon too.
<?php
$path = 'files/my report.pdf';
$encoded = implode('/', array_map('rawurlencode', explode('/', $path)));
$url = 'https://api.example.com/' . $encoded; // https://api.example.com/files/my%20report.pdf3Verify
The URL holds no whitespace, and the status code is no longer 400.
<?php
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), "\n";Confirmed by php.net
Cause 2 of 3
A query-string value holds a space
1Check
Values glued onto the URL as they are keep their spaces. PHP can build the query string for you and encode each value.
<?php
echo $url, "\n";2Fix
Build the query string from an array. The default encoding turns a space into a plus sign. If the API wants %20, pass PHP_QUERY_RFC3986 as the fourth argument.
<?php
$params = ['q' => 'hypertext processor', 'page' => 2];
$url = 'https://api.example.com/search?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
// https://api.example.com/search?q=hypertext%20processor&page=23Verify
Send the request again and read the status code.
<?php
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), "\n";Confirmed by php.net
Cause 3 of 3
Whitespace at the start or end of the URL came from its source
1Check
A URL read from a file, a database field, a CSV or an environment file often carries a trailing newline or space. The standard allows no whitespace in the request target. Compare the printed length with what you expect.
<?php
var_dump(strlen($url), strlen(trim($url)));2Fix
Trim the URL once, right where it is read. By default trim() strips spaces, tabs, line breaks and NUL bytes from both ends.
<?php
$url = trim($url);3Verify
Both lengths in the check are equal, and the request returns its normal status.
<?php
var_dump(strlen($url) === strlen(trim($url)));Confirmed by php.net
How do I stop it coming back?
- Never join user text or file names onto a URL directly; encode them first.
- Encode path segments with rawurlencode() and query parameters with http_build_query(), each in its own place.
- Log the final URL and the status code of every outbound request, so a 400 is traced in seconds.
- Trim values read from files and databases at the moment you read them.
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
PHP cURL request fails with 411 Length Required
HTTP/1.1 411 Length Required
A 411 means the server refuses a request that does not state its body length.
2 causes, each with a fixBack end
A PHP cURL request hangs, times out, or fails with no message
curl_exec() returns false and nothing is shown
PHP's cURL has no timeout of its own: CURLOPT_TIMEOUT defaults to 0 (never) and the connect phase waits up to 300 seconds.
4 causes, each with a fixBack 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 fix