Urlencode and file_get_contents

2020-02-12 05:37发布

We have an url like http://site.s3.amazonaws.com/images/some image @name.jpg inside $string

What I'm trying to do (yes, there is a whitespace around the url):

$string = urlencode(trim($string));
$string_data = file_get_contents($string);

What I get (@ is also replaced):

file_get_contents(http%3A%2F%2Fsite.s3.amazonaws.com%2Fimages%2Fsome+image+@name.jpg)[function.file-get-contents]: failed to open stream: No such file or directory

If you copy/paste http://site.s3.amazonaws.com/images/some image @name.jpg into browser address bar, image will open.

What's bad and how to fix that?

2条回答
叼着烟拽天下
2楼-- · 2020-02-12 06:11

Using function urlencode() for entire URL, will generate an invalid URL. Leaving the URL as it is also is not correct, because in contrast to the browsers, the file_get_contents() function don't perform URL normalization. In your example, you need to replace spaces with %20:

$string = str_replace(' ', '%20', $string);
查看更多
再贱就再见
3楼-- · 2020-02-12 06:17

The URL you have specified is invalid. file_get_contents expects a valid http URI (more precisely, the underlying http wrapper does). As your invalid URI is not a valid URI, file_get_contents fails.

You can fix this by turning your invalid URI into a valid URI. Information how to write a valid URI is available in RFC3986. You need to take care that all special characters are represented correctly. e.g. spaces to plus-signs, and the commercial at sign has to be URL encoded. Also superfluous whitespace at beginning and end need to be removed.

When done, the webserver will tell you that the access is forbidden. You then might need to add additional request headers via HTTP context options for the HTTP file wrapper to solve that. You find the information in the PHP manual: http:// -- https:// — Accessing HTTP(s) URLs

查看更多
登录 后发表回答