Maaz Zindani

Loading the index…

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

PHP cURL gets 400 Bad Request because the URL contains a space

Error400 Bad Request

Short 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.

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

Fix it fast

  1. 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));
  2. 2Match what you see, then jump to its fix

    1. 1The URL has a file or folder name with a space in it, such as /files/my report.pdfA path segment holds a spaceFix
    2. 2The URL was built with string concatenation, such as '?q=' . $text, and the text has spacesA query-string value holds a spaceFix
    3. 3preg_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

What does the error look like?

  • 400 Bad Request
  • The 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.pdf

3Verify

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

Did this fix it?

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=2

3Verify

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

Did this fix it?

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

Did this fix it?

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

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.