Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl returns 400 bad request (url with spaces)

Tags:

php

curl

When i use curl library and try to get image from url i get 400 bad request error. I founded that problem is with encoding url. But in my case it's not work, because my url - it's path to image on server side - like

http://example.com/images/products/product 1.jpg

I understand that user spaces in name files it's bad practice, but it's not my server and not i created those files.

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

When i use urlencode function - curl return http_code = 0

Updated

$url = str_replace(' ', '+', $url);

doesn't work, server return 404 error.

like image 435
yAnTar Avatar asked Sep 09 '12 19:09

yAnTar


2 Answers

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);
like image 196
Wim Molenberghs Avatar answered Sep 23 '22 10:09

Wim Molenberghs


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.

like image 39
Alexander Yancharuk Avatar answered Sep 23 '22 10:09

Alexander Yancharuk