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

心不动则不痛 提交于 2019-11-29 07:02:57

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.

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

Here is maybe a better solution. If for any reason you are using a relative url like:

//www.example.com/path

Prior to php 5.4.7 this would not create the [scheme] array element which would throw off maček function. This method may be faster as well.

$url = '//www.example.com/path';

preg_match('/(https?:\/\/|\/\/)([^\/]+)(.*)/ism', $url, $result);

$url = $result[1].$result[2].urlencode(urldecode($result[3])); 

Assuming only the file name has the problem, this is a better approach. only urlencode the last section ie. file name.

private function update_url($url)
{
    $parts = explode('/', $url);

    $new_file = urlencode(end($parts));
    $parts[key($parts)] = $new_file;

    return implode("/", $parts);
}

This should work

$file = 'some file name';
urlencode($file);
file_get_contents($file);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!