简体   繁体   中英

Echo modified time of file

I am trying to get the modified time of my css file. I have tried the following:

$filename = '/~site/templates/mytemplate/css/template.css';
$filename2 = "/~site/templates/mytemplate/test.html";

echo "Last modified: " . date ("F d Y H:i:s.", filemtime($filename)) ."<br>";
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod($filename)) ."<br>"

echo "Last modified: " . date ("F d Y H:i:s.", filemtime($filename2)) ."<br>";
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod($filename2)) ."<br>";

Returns

Last modified: December 31 1969 18:00:00.

Last modified: November 06 2013 09:18:52.

Last modified: December 31 1969 18:00:00.

Last modified: November 06 2013 09:18:52.

But the actual mod date was yesterday, so it should be November 18 2013 16:01:00 The second file was this morning and I just created it to test!

What am I doing wrong? Is it the server returning the wrong date?

filemtime() returns FALSE on failure. That's why you're receiving Last modified: December 31 1969 18:00:00 on output. FALSE evaluates to 0 so:

date("F d Y H:i:s.", 0) == 'January 01 1970 00:00:00'

(minus 6 hours due to your timezone, I guess).
The reason that filemtime() returns FALSE is probably the $filename doesn't exist. You should check it first:

if (file_exists($filename)) {
    echo "Last modified: " . date ("F d Y H:i:s.", filemtime($filename)) ."<br>";
}

The problem with getlastmod() is obvious. As we can read in the documentation , this function

Gets the time of the last modification of the main script of execution

EDIT : According to the discussion in the comments below this answer - the solution was to cut down the path to the file to:

$filename = 'css/template.css';

Maybe take a look at the notes in the bottom of the following link :

http://php.net/manual/en/function.filemtime.php

Or can you try with stat() function ?

$stat = stat('path/to/file');
echo 'Modification time: ' . $stat['mtime'];

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