note 83990 added to function.opendir

From: Date: Sun, 22 Jun 2008 17:20:11 +0000
Subject: note 83990 added to function.opendir
Groups: php.notes 
Request: Send a blank email to php-notes+get-140722@lists.php.net to get a copy of this message
Here are two versions of the same function to list all files in a directory tree. The first one is recursive (calls itself while going through subdirectories) : <?php function rec_listFiles( $from = '.') { if(! is_dir($from)) return false; $files = array(); if( $dh = opendir($from)) { while( false !== ($file = readdir($dh))) { // Skip '.' and '..' if( $file == '.' || $file == '..') continue; $path = $from . '/' . $file; if( is_dir($path) ) $files += rec_listFiles($path); else $files[] = $path; } closedir($dh); } return $files; } ?> The second one is iterative (uses less memory) : <?php function listFiles( $from = '.') { if(! is_dir($from)) return false; $files = array(); $dirs = array( $from); while( NULL !== ($dir = array_pop( $dirs))) { if( $dh = opendir($dir)) { while( false !== ($file = readdir($dh))) { if( $file == '.' || $file == '..') continue; $path = $dir . '/' . $file; if( is_dir($path)) $dirs[] = $path; else $files[] = $path; } closedir($dh); } } return $files; } ?> The iterative version should be a little faster most of the time, but the big difference is in the memory usage. Here is also a profiling function (works in php5 only) : <?php function profile( $func, $trydir) { $mem1 = memory_get_usage(); echo '<pre>----------------------- Test run for '.$func.'() ... '; flush(); $time_start = microtime(true); $list = $func( $trydir); $time = microtime(true) - $time_start; echo 'Finished : '.count($list).' files</pre>'; $mem2 = memory_get_peak_usage(); printf( '<pre>Max memory for '.$func.'() : %0.2f kbytes Running time for '.$func.'() : %0.f s</pre>', ($mem2-$mem1)/1024.0, $time); return $list; } ?> ---- Server IP: 217.174.223.124 Probable Submitter: 80.13.176.197 ---- Manual Page -- http://www.php.net/manual/en/function.opendir.php Edit -- https://master.php.net/note/edit/83990 Del: integrated -- https://master.php.net/note/delete/83990/integrated Del: useless -- https://master.php.net/note/delete/83990/useless Del: bad code -- https://master.php.net/note/delete/83990/bad+code Del: spam -- https://master.php.net/note/delete/83990/spam Del: non-english -- https://master.php.net/note/delete/83990/non-english Del: in docs -- https://master.php.net/note/delete/83990/in+docs Del: other reasons-- https://master.php.net/note/delete/83990 Reject -- https://master.php.net/note/reject/83990 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140722) next »