Can we get the time and size of the directory, i.e. statistics?

Can we get the time and size of the directory modified by the directory, i.e. statistics in php? How?

+4
source share
3 answers

Yes. You can use the stat function

$stat = stat('\path\to\directory'); echo 'Modification time: ' . $stat['mtime']; // will show unix time stamp. echo 'Size: ' . $stat['size']; // in bytes. 
+11
source

You can get the modified time using filemtime or SplFileInfo::getMTime .

How to get the size of a directory, do you mean the file size of all the contents inside it (it might seem like a silly question, the size is ambiguous)?

If you only need the recorded 'filesize' directory, then filesize or SplFileInfo::getSize should be enough.

 $dir = new SplFileInfo('path/to/dir'); printf( "Directory modified time is %s and size is %d bytes.", date('d/m/YH:i:s', $dir->getMTime()), $dir->getSize() ); 
+4
source

For me, using filemtime worked fine.

Example

 <?php $path_to_file = '/tmp/'; echo filemtime($path_to_file); // 1380387841 

Even if it is called the "mtime file", it also works for directories.

Caveat / gotcha

Make sure the file or directory that you are checking exists, otherwise you will get something like:

filemtime (): stat failed for / asdfasdfasdf in test.php on line 3

Possible fixes include something β€œcorrect”:

 $path = '/tmp/'; $mtime = file_exists($path)?filemtime($path):''; 

And something less verbose but hacked using the error suppression operator ( @ ):

 $path = '/tmp/'; $mtime = @filemtime($path); 

From manual

filemtime ()

int filemtime (string $ filename )

This function returns the time when the data blocks of the file were written, that is, the time when the contents of the file were changed.

+3
source

Source: https://habr.com/ru/post/1308880/


All Articles