Can we get the Directory's Modified time and size i.e. stats?
Can we get the Dir开发者_开发技巧ectory's Modified time and size i.e. stats in php? How?
Yes. You can make use of stat function
$stat = stat('\path\to\directory');
echo 'Modification time: ' . $stat['mtime']; // will show unix time stamp.
echo 'Size: ' . $stat['size']; // in bytes.
You can get the modified time with filemtime
or SplFileInfo::getMTime
.
As for getting the size of the directory, do you mean the file size of all of the contents within it (might sound like a silly question, size is ambiguous)?
If you are wanting just the recorded 'filesize' of the directory then filesize
or SplFileInfo::getSize
should suffice.
$dir = new SplFileInfo('path/to/dir');
printf(
"Directory modified time is %s and size is %d bytes.",
date('d/m/Y H:i:s', $dir->getMTime()),
$dir->getSize()
);
For me using filemtime
worked just fine.
Example
<?php
$path_to_file = '/tmp/';
echo filemtime($path_to_file); // 1380387841
Even though it is called "file mtime" it works for directories, too.
Caveat / Gotcha
Make sure the file or directory you are checking exists otherwise you'll get something like:
filemtime(): stat failed for /asdfasdfasdf in test.php on line 3
Possible fixes include something 'proper':
$path = '/tmp/';
$mtime = file_exists($path)?filemtime($path):'';
And something less verbose but hacky by using the error suppression operator (@
):
$path = '/tmp/';
$mtime = @filemtime($path);
From the manual
filemtime()
int filemtime ( string $filename )
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.
精彩评论