file_get_contents false 当 url 有空格时(编码一切无效)

file_get_contents false when url have spaces (encode everything not working)

所以,问题出在这一行

$imageString = file_get_contents($image_url);

具有 space 字符的网址无效。但是如果我让

$imageString = file_get_contents(urlencode($image_url));

Nothing works.I 不断在变量中接收 false。

ulr 是这样的:

https://s3-eu-central-1.amazonaws.com/images/12/Screenshot from 2016-04-28 18 15:54:20.png

使用这个功能

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

我遇到过同样的问题,如果你搜索它,你会看到所有人都告诉你使用 urlencode(),但是不行! ! urlencode() 在这种情况下无法工作...

我使用了 @Akram Wahid 的答案并且效果很好所以我推荐它用于 file_get_contents()。

如果您想知道 escapefile_url() 中做了什么@Akram Wahid 在这里回答一点解释:

只是他将 url 拆开作为数组,然后他使用 rawurlencode() 对所有包含特殊字符的部分进行编码,而不是主域如 (http://example.com).

那有什么尊重?!!这里的例子使用 urlencode()escapefile_url() 来澄清这个

echo escapefile_url("http://example.com/foo/bar bof/some file.jpg") . "<br>";
// http://example.com/foo/bar%20bof/some%20file.jpg

echo urlencode("http://example.com/foo/bar bof/some file.jpg") . "<br>";
// http%3A%2F%2Fexample.com%2Ffoo%2Fbar+bof%2Fsome+file.jpg

如果您想将@Akram Wahid 的解决方案应用于也可能包含 GET 参数的 URL,那么更新版本将是这样的:

function escapefile_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)) .
    (isset($parts['query']) ? '?'.rawurldecode($parts['query']) : '')
  ;
}