filemtime() [function.filemtime]: stat failed for filenames with umlauts

Benny Neugebauer picture Benny Neugebauer · Oct 3, 2011 · Viewed 35.1k times · Source

I use the PHP function filemtime to get the last modification time with PHP 5.3. This functions works very well but it seems to have some problems when the filenames have special characters (for example umlauts).

If I run it on a filename with umlauts

$stat = filemtime('C:/pictures/München.JPG');

then I get the output:

Warning: filemtime() [function.filemtime]: stat failed for C:/pictures/München.JPG

If I rename the file from "München.JPG" to "Muenchen.JPG" and do the same thing again:

 $stat = filemtime('C:/pictures/Muenchen.JPG');

everything works fine!

My PHP file is saved as UTF-8 without BOM and I also tried:

clearstatcache();
$stat = filemtime(utf8_encode('C:/pictures/München.JPG'));

but it has not helped.

Answer

Benny Neugebauer picture Benny Neugebauer · Oct 4, 2011

With the following code snippet I found out that the file encoding on Windows 7 is "ISO-8859-1":

$scandir = scandir('.')
$encoding = mb_detect_encoding($scandir[0], 'ISO-8859-1, UTF-8, ASCII');
echo $encoding;

I've read that utf8_decode converts a UTF-8 string to ISO-8859-1 so I ended up with this small code that works for my project:

$file = 'C:/pictures/München.JPG';
$lastModified = @filemtime($file);
if($lastModified == NULL)
    $lastModified = filemtime(utf8_decode($file));
echo $lastModified;

Thank you to all who have submitted a comment. You have steered me in the right direction. :-)