简体   繁体   中英

file_get_contents - special characters in URL

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM