Urlencode and file_get_contents

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

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

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

What I get (@ 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 the address bar of your browser, an image will open.

What is bad and how to fix it?

+7
source share
2 answers

The specified URL is not valid. file_get_contents expects a valid http URI (more specifically, the main http shell). Since 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 on how to write a valid URI is available in RFC3986 . You must ensure that all special characters are correctly represented. for example, spaces before plus signs, and the commercial sign must be encoded in the URL. It is also necessary to remove extra spaces at the beginning and end.

When this is done, the web server will tell you that access is denied. You may then need to add additional request headers through the HTTP context options to wrap the HTTP file in order to solve this problem. You will find information in the PHP manual: http: // - https: // - Access to HTTP URLs

+1
source

Using the urlencode() function for an entire URL will result in an invalid URL. Leaving with a URL is also not correct, because unlike browsers, the file_get_contents() function does not normalize the URL . In your example, you need to replace the spaces with %20 :

 $string = str_replace(' ', '%20', $string); 
+9
source

All Articles