6

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.

yAnTar
  • 4,269
  • 9
  • 47
  • 73
  • 3
    is such a URL possible ( with space ). Space turns into `%20` when we type space in URL – xkeshav Sep 09 '12 at 19:26
  • 1
    @diEcho what? of course it is possible. It doesn't turn into %20 by itself - some clients can do that, but certainly not all of them, and always it isn't even possible. – eis Sep 09 '12 at 19:34

4 Answers4

28

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);
Wim Molenberghs
  • 882
  • 8
  • 7
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.

Community
  • 1
  • 1
Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
0

You can't urlencode the entire string because that will encode the slashes and others that you need to remain unencoded. If spaces are your only problem, this will do:

str_replace(' ', '+', $url);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
-1

Using curl has more challenges than other ways. Simply use shell_exec

$cmd = "curl -k -v -X POST 'https://serveraddress:8243/?foo=bar' -H 'Authorization: Basic cEZ.....h'";

$result = shell_exec($cmd);         
$output =  json_decode($result,true);
print_r($output);           
ganji
  • 752
  • 7
  • 17