Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we get the Directory's Modified time and size i.e. stats?

Tags:

php

Can we get the Directory's Modified time and size i.e. stats in php? How?

like image 418
OM The Eternity Avatar asked May 05 '10 12:05

OM The Eternity


3 Answers

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.
like image 192
codaddict Avatar answered Oct 03 '22 02:10

codaddict


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()
);
like image 25
salathe Avatar answered Oct 03 '22 02:10

salathe


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.

like image 29
cwd Avatar answered Oct 03 '22 00:10

cwd