Home » Php » php – Urlencode and file_get_contents

php – Urlencode and file_get_contents

Posted by: admin July 12, 2020 Leave a comment

Questions:

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%[email protected])[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?

How to&Answers:

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

Answer:

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);