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

character-encoding, filesystems, linux, php, windows

Solution

The best way would be to detect if your using Windows server or not. From that you can apply the right command

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'This is a server using Windows!';
} else {
    echo 'This is a server not using Windows!';
}

Problem

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.

Original source