Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - file_get_contents - Downloading files with spaces in the filename not working

I am trying to download files using file_get_contents() function. However if the location of the file is http://www.example.com/some name.jpg, the function fails to download this.

But if the URL is given as http://www.example.com/some%20name.jpg, the same gets downloaded.

I tried rawurlencode() but this coverts all the characters in the URL and the download fails again.

Can someone please suggest a solution for this?

like image 805
user1064386 Avatar asked Nov 24 '11 17:11

user1064386


2 Answers

I think this will work for you:

function file_url($url){
  $parts = parse_url($url);
  $path_parts = array_map('rawurldecode', explode('/', $parts['path']));

  return
    $parts['scheme'] . '://' .
    $parts['host'] .
    implode('/', array_map('rawurlencode', $path_parts))
  ;
}


echo file_url("http://example.com/foo/bar bof/some file.jpg") . "\n";
echo file_url("http://example.com/foo/bar+bof/some+file.jpg") . "\n";
echo file_url("http://example.com/foo/bar%20bof/some%20file.jpg") . "\n";

Output

http://example.com/foo/bar%20bof/some%20file.jpg
http://example.com/foo/bar%2Bbof/some%2Bfile.jpg
http://example.com/foo/bar%20bof/some%20file.jpg

Note:

I'd probably use urldecode and urlencode for this as the output would be identical for each url. rawurlencode will preserve the + even when %20 is probably suitable for whatever url you're using.

like image 153
maček Avatar answered Sep 22 '22 08:09

maček


As you have probably already figured out urlencode() should only be used on each portion of a URL that requires escaping.

From the docs for urlencode() just apply it to the image file name giving you the problem and leave the rest of the URL alone. From your example you can safely encode everything following the last "/" character

like image 21
Brad Avatar answered Sep 19 '22 08:09

Brad