Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

urlencode - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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") . "
";
echo file_url("http://example.com/foo/bar+bof/some+file.jpg") . "
";
echo file_url("http://example.com/foo/bar%20bof/some%20file.jpg") . "
";

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...