tags:

views:

253

answers:

3

If we don't use exec("ls -l") in PHP, but use readdir() or scandir() to get the list of files, and want to list the file sizes and maybe modification date as well, do we need to call stat() 1000 times if there are 1000 files? Is there a simpler or faster way?

Will calling stat() 1000 times hit the file system a lot? Or maybe the OS will cache all the data in memory so it involves only access to RAM but not to the disk.

Update: it looks good to use DirectoryIterator(), but how do you sort the items?

+3  A: 

LS calls the stat function in the background for you. Listing a directory will only give you the names of the files/folders in question, so you must manually stat each filename returned to get information about each file itself. So yes, you must call stat 1000 times for 1000 files to get all their info. Ideally you will do it in loop.

futureelite7
i don't of any other way if it is not done in a loop, haha
動靜能量
@Jian Lin: Copy )
musicfreak
manually hard-coding each call? j/k ;-)
Carlos Lima
A: 

If you don't need all the info from stat, and to not have to parse the output from exec("stat $filename"), you could use the "specialized" PHP commands, i.e. filectime for modified date, filesize for size etc.

EDIT: And now I learned a new command :) PHP has fstat, which returns an assoc array. Maybe filectime uses this internally? Anyway, don't use exec stat and parse it.

carlpett
+1  A: 

Why using exec() command? This is cleaner and a good solution if you have php5.x. :)

$files = new DirectoryIterator('/www/test/');
foreach ($files as $file) {
  if ($file->isFile()) echo $file->getSize();
}

http://php.net/manual/en/book.spl.php

Toto
that looks good except is there a way to sort the filenames alphabetically? thanks.
動靜能量
Unfortunately this class has not this usefull method. You can (A) extend (PHP) this class and add such a method or (B) assign the result to an array and then sort it. But it is a very common request, so I am sure we will have a builtin sort() method in a future release of php. :)
Toto