php - file_get_contents - 下载文件名中带空格的文件不起作用

use*_*386 7 php urlencode file-get-contents

我正在尝试使用file_get_contents()函数下载文件.但是,如果文件的位置是http://www.example.com/some name.jpg,则该功能无法下载.

但是如果URL被给出http://www.example.com/some%20name.jpg,则下载相同的URL .

我试过rawurlencode()但是这会隐藏URL中的所有字符,下载再次失败.

有人可以为此建议一个解决方案吗?

mač*_*ček 25

我认为这对你有用:

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";
Run Code Online (Sandbox Code Playgroud)

产量

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
Run Code Online (Sandbox Code Playgroud)

注意:

我可能会使用urldecodeurlencode为此,因为每个网址的输出都是相同的. rawurlencode将保留+甚至什么时候%20可能适合你正在使用的任何网址.


Bra*_*rad 2

您可能已经发现 urlencode() 应该只用在需要转义的 URL 的每个部分。

urlencode() 的文档中,只需将其应用于给您带来问题的图像文件名,并保留 URL 的其余部分。从您的示例中,您可以安全地对最后一个“/”字符后面的所有内容进行编码