I noticed on my UNIX testing box if the file/folder is not chmodded with the executable bit it will fail. So just make sure to chmod all files with executable rights...If someone knows a work around please email me at r o t_ nata li c w [at] y ah oo . c o m -- Remove spaces. I am developing a cms so I need this.
filemtime
(PHP 4, PHP 5)
filemtime — 取得文件修改时间
说明
int filemtime
( string $filename
)
返回文件上次被修改的时间,出错时返回 FALSE。时间以 Unix 时间戳的方式返回,可用于 date()。
Note: 本函数的结果会被缓存。更多信息参见 clearstatcache()。
Tip
自 PHP 5.0.0 起本函数也可被某些 URL wrapper 使用。参考支持的协议/封装协议列表 来看哪些 wrapper 支持 stat() 系列函数的功能。
本函数返回文件中的数据块上次被写入的时间,也就是说,文件的内容上次被修改的时间。
Example#1 filemtime() 例子
<?php
// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>
参见 filectime(),stat(),touch() 和 getlastmod()。
filemtime
Natalic
15-Jun-2008 12:34
15-Jun-2008 12:34
kbrobst at surveyresearchpartners dot com
31-Mar-2008 12:56
31-Mar-2008 12:56
I created an application which stores files as blobs in a database, and retrieves them upon user request (into a webDAV-enabled area). The files are touched so that they have the correct timestamp information after being retrieved. After the user is done making any alterations, a script runs that checks for changes in the files (including timestamps).
It appears that working with timestamps on files under Windows systems (XP/Server 2003) is a problem, because the timestamp on files, for example, will toggle between 1pm and 2pm depending on the age of the file and if it is DST or not.
Try this experiment:
$timestamp_str = "2005.02.06 14:45:33";
$timestamp_pieces=split('[. :]',$timestamp_str);
$timestamp=mktime($timestamp_pieces[3], $timestamp_pieces[4], $timestamp_pieces[5], $timestamp_pieces[1], $timestamp_pieces[2], $timestamp_pieces[0]);
touch("c:\\timestamp_test.txt",$timestamp);
The file timestamp_test.txt shows up in the operating system as having a modification date of "Sunday, February 06, 2005, 2:45:33 PM" - which is the desired result.
But now look at the results of filemtime (only when in DST - it will report the correct timestamp during standard time):
$compare_timestamp=filemtime("c:\\timestamp_test.txt");
$compare_timestamp_str = date("Y.m.d H:i:s",$compare_timestamp);
echo "$timestamp ($timestamp_str) is the original timestamp.<br />\n";
echo "$compare_timestamp ($compare_timestamp_str) is the timestamp on the file.<br />\n";
The output looks like this:
1107726333 (2005.02.06 14:45:33) is the original timestamp.
1107722733 (2005.02.06 13:45:33) is the timestamp on the file.
The filemtime function reports a timestamp different from what the OS reports. You'll likely need to code around this issue if you are attempting something similar - because this is not a PHP bug but a "Microsoft feature".
geeks at geekman dot info
18-Feb-2008 01:01
18-Feb-2008 01:01
This is a very handy function for dealing with browser caching. For example, say you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a pain in the ass. Instead, you can do this:
<?
echo '
<link rel="stylesheet" type="text/css" href="style.css?' . filemtime('style.css') . '" />';
?>
Sample output:
<link rel="stylesheet" type="text/css" href="style.css?1203291283" />
By appending a GET value (the UNIX timestamp) to the stylesheet URL, you make the browser think the stylesheet is dynamic, so it'll reload the stylesheet every time the modification date changes.
solarijj at gmail dot com
09-Mar-2007 04:02
09-Mar-2007 04:02
To get the modification date of some remote file, you can use the fine function by notepad at codewalker dot com (with improvements by dma05 at web dot de and madsen at lillesvin dot net).
But you can achieve the same result more easily now with stream_get_meta_data (PHP>4.3.0).
However a problem may arise if some redirection occurs. In such a case, the server HTTP response contains no Last-Modified header, but there is a Location header indicating where to find the file. The function below takes care of any redirections, even multiple redirections, so that you reach the real file of which you want the last modification date.
hih,
JJS.
<?php
// get remote file last modification date (returns unix timestamp)
function GetRemoteLastModified( $uri )
{
// default
$unixtime = 0;
$fp = fopen( $uri, "r" );
if( !$fp ) {return;}
$MetaData = stream_get_meta_data( $fp );
foreach( $MetaData['wrapper_data'] as $response )
{
// case: redirection
if( substr( strtolower($response), 0, 10 ) == 'location: ' )
{
$newUri = substr( $response, 10 );
fclose( $fp );
return GetRemoteLastModified( $newUri );
}
// case: last-modified
elseif( substr( strtolower($response), 0, 15 ) == 'last-modified: ' )
{
$unixtime = strtotime( substr($response, 15) );
break;
}
}
fclose( $fp );
return $unixtime;
}
?>
bastiaan nelissen
21-Dec-2006 10:20
21-Dec-2006 10:20
"This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed."
Well, the content of the file does not need to 'change'. Saving file content without changes will be enough.
Understanding this helped me.
Benan Tumkaya (benantumkaya at yahoo)
14-Aug-2006 05:11
14-Aug-2006 05:11
Here is a small but handy script that you can use to find which files in your server are modified after a date/time that you specify. This script will go through all folders in the specified directory recursively and echo the modified files with the last modified date/time...
//Starts Here
//Put here the directory you want to search for. Put / if you want to search your entire domain
$dir='/';
//Put the date you want to compare with in the format of: YYYY-mm-dd hh:mm:ss
$comparedatestr="2006-08-12 00:00:00";
$comparedate=strtotime($comparedatestr);
//I run the function here to start the search.
directory_tree($dir,$comparedate);
//This is the function which is doing the search...
function directory_tree($address,$comparedate){
@$dir = opendir($address);
if(!$dir){ return 0; }
while($entry = readdir($dir)){
if(is_dir("$address/$entry") && ($entry != ".." && $entry != ".")){
directory_tree("$address/$entry",$comparedate);
}
else {
if($entry != ".." && $entry != ".") {
$fulldir=$address.'/'.$entry;
$last_modified = filemtime($fulldir);
$last_modified_str= date("Y-m-d h:i:s", $last_modified);
if($comparedate < $last_modified) {
echo $fulldir.'=>'.$last_modified_str;
echo "<BR>";
}
}
}
}
}
csnyder at chxo dot com
11-Aug-2006 11:59
11-Aug-2006 11:59
If PHP's integer type is only 32 bits on your system, filemtime() will fail on files over 2GB with the warning "stat failed". All stat()-related commands will exhibit the same behavior.
As a workaround, you can call the system's stat command to get the modification time of a file:
On FreeBSD:
$mtime = exec ('stat -f %m '. escapeshellarg ($path));
On Linux:
$mtime = exec ('stat -c %Y '. escapeshellarg ($path));
Thanks to "mpb dot mail at gmail dot com" for his/her similar comment on stat().
madsen at lillesvin dot net
26-Sep-2005 06:39
26-Sep-2005 06:39
There are a couple of things to point out about the otherwise great example posted by "notepad at codewalkers dot com".
First of all, as "dma05 at web dot de" pointed out, use HEAD instead of GET - that's being nice to your fellow man.
Second, it will only allow communication on port 80. That can easilly be solved.
<?php
function remote_filemtime($url)
{
$uri = parse_url($url);
$uri['port'] = isset($uri['port']) ? $uri['port'] : 80;
$handle = @fsockopen($uri['host'], $uri['port']);
// ...
}
?>
But hey, thanks a lot for the function! I've really had great use of it.
dma05 at web dot de
24-Apr-2005 05:25
24-Apr-2005 05:25
concerning "notepad at codewalkers dot com"'s code:
this code is pretty neat, but i just wanted to note that using the "HEAD"-method instead of the "GET"-method in the http-request might be preferrable, since then not the whole resource is being downloaded...
http/1.1 definiton snippet:
Section "9.4 HEAD"
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. [...]
-- snippet end ---
the code would then be...:
-- snippet ---
fputs($handle,"HEAD $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
-- snippet end ---
regards, Magnus
notepad at codewalkers dot com
11-Mar-2005 05:53
11-Mar-2005 05:53
i needed the ability to grab the mod time of an image on a remote site. the following is the solution with the help of Joe Ferris.
<?php
function filemtime_remote($uri)
{
$uri = parse_url($uri);
$handle = @fsockopen($uri['host'],80);
if(!$handle)
return 0;
fputs($handle,"GET $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
$result = 0;
while(!feof($handle))
{
$line = fgets($handle,1024);
if(!trim($line))
break;
$col = strpos($line,':');
if($col !== false)
{
$header = trim(substr($line,0,$col));
$value = trim(substr($line,$col+1));
if(strtolower($header) == 'last-modified')
{
$result = strtotime($value);
break;
}
}
}
fclose($handle);
return $result;
}
// echo filemtime_remote('http://www.somesite.com/someimage.jpg');
?>
habazi at yahoo dot com
22-Feb-2005 02:13
22-Feb-2005 02:13
"this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it's sub directories)."
This is not (necessarily) correct either. In *nix the timestamp can be independently set. For example the command "touch directory" updates the timestamp of a directory without file creation.
Also file removal will update the timestamp of a directory.
10-Dec-2004 12:30
A comment below states
"When using this function to get the modified date of a directory,
it returns the date of the file in that directory that was last modified."
this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it's sub directories).
aidan at php dot net
26-Oct-2004 08:42
26-Oct-2004 08:42
If you're looking to convert timestamps to a duration, for example "10" to "10 seconds", or "61" to "1 minute 1 second", try the Duration class.
http://aidanlister.com/repos/v/Duration.php
adam at roomvoter dot com
02-May-2004 04:42
02-May-2004 04:42
The snippet of code earlier that allows you to delete all files older than 2 weeks uses the function (filemtime) - which checks the original create date of the file (filesystem independent). You MAY want to use filectime() - that looks at when the file was last changed on YOUR file system.
if (is_dir("$path") )
{
$handle=opendir($path);
while (false!==($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$Diff = (time() - filectime("$path/$file"))/60/60/24;
if ($Diff > 14) unlink("$path/$file");
}
}
closedir($handle);
}
wookie at at no-way dot org
15-Sep-2003 05:17
15-Sep-2003 05:17
Another little handy tool; to get the most recent modified time from files in a directory. It even does recursive directories if you set the $doRecursive param to true. Based on a file/directory list function I saw somewhere on this site. ;)
function mostRecentModifiedFileTime($dirName,$doRecursive) {
$d = dir($dirName);
$lastModified = 0;
while($entry = $d->read()) {
if ($entry != "." && $entry != "..") {
if (!is_dir($dirName."/".$entry)) {
$currentModified = filemtime($dirName."/".$entry);
} else if ($doRecursive && is_dir($dirName."/".$entry)) {
$currentModified = mostRecentModifiedFileTime($dirName."/".$entry,true);
}
if ($currentModified > $lastModified){
$lastModified = $currentModified;
}
}
}
$d->close();
return $lastModified;
}
paranoid at dds dot nl
05-Jun-2003 08:43
05-Jun-2003 08:43
To get the last modification time of a directory, you can use this:
<pre>
$getLastModDir = filemtime("/path/to/directory/.");
</pre>
Take note on the last dot which is needed to see the directory as a file and to actually get a last modification date of it.
This comes in handy when you want just one 'last updated' message on the frontpage of your website and still taking all files of your website into account.
Regards,
Frank Keijzers
laurent dot pireyn at wanadoo dot be
27-Sep-2001 08:00
27-Sep-2001 08:00
If you use filemtime with a symbolic link, you will get the modification time of the file actually linked to. To get informations about the link self, use lstat.
24-Aug-2001 10:08
When using this function to get the modified date of a directory, it returns the date of the file in that directory that was last modified.
jay at fudge dot org
30-Jun-1999 04:55
30-Jun-1999 04:55
If you want this functionality for the parent web page you should use getlastmod()
i.e.
<?php echo "Last modified: ".date( "F d Y H:i:s.", getlastmod() ); ?>
within the included page... i.e. as a commont footer include for all pages
gerardj at home dot com
20-May-1999 11:27
20-May-1999 11:27
The above code works fine if you place it on each page you want a date stamp on. I've found that if you place a reference such as filemtime(__FILE__) in an included or required file, that the modification time of the inherited file will be returned, not the time of the file that did the ineriting.
