Curl returns 400 bad request (url with spaces)

Solution 1:

Does this maybe work?

$url = 'http://host/a b.img';
$url = str_replace(" ", '%20', $url);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
echo $ret = curl_exec($ch);

Solution 2:

You need to use rawurlencode() function:

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, rawurlencode($url));
echo $ret = curl_exec($ch);

rawurlencode() must be always preferred. urlencode() is only kept for legacy use. For more details look at this SO answer.