Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents - special characters in URL

Tags:

php

I am trying to get images from a remote server using file_get_contents. A URL to an image may contain spaces and/or special characters like ý, á, í, etc and when it does the operation fails with a HTTP code 400 - Bad Request. If I try to encode the url (or segments of that URL), using urlencode or rawurlencode, I get a 404.

When the image URL does not contain spaces nor special chars it is downloaded without problems.

I have a hunch that this has got something to do with encoding but I just can't figure it out. Is there an encoding option I'm missing? Is there a header that must be set for the request?

like image 826
Jón Óskar Avatar asked May 01 '12 11:05

Jón Óskar


1 Answers

The problem with file_get_contents is the UTF-8 encoding (didn't implemented yet in PHP) If you want download file with this function, you have to do something like that on your URL:

$url_utf8 = rawurlencode(utf8_encode($url));

And after:

$content = file_get_contents($url_utf8);

like image 181
Jacky Lormoz Avatar answered Nov 11 '22 04:11

Jacky Lormoz