Why does Windows need to `utf8_decode` filenames for `file_get_contents` to work?

By | March 30, 2018
Questions:

If $filename contains umlauts (ä,ö,ü) file_get_contents($filename) doesn’t work on my Windows OS. By trial and error I found out that I need to do file_get_contents(utf8_decode($filename)) to get it to work.

However, when I pushed this live to my server (guess it’s some kind of Linux) it returned an error again, so I removed the utf8_decode and suddenly it worked perfectly.

As a workaround (so I don’t need to change this piece of code manually every time I make changes to the code) I already tried

(mb_detect_encoding($filename, 'UTF-8', true)) ? utf8_decode$filename) : $filename;

as this already worked for the same problem the other way round (had the same problem with utf8_encode), but $filename turned out to be UTF8-encoded in every (server) environment, so this doesn’t work, as it’s always true.

Any ideas how to get this to work on both systems? (Please no “just migrate to Linux for PHP development”—I’ve got Linux, but ATM I’m using Windows for a number of reasons)


Edit: the problem appears also with fopen and the accepted solution works as well.

Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *