[thelist] PHP- get list of files in directory?

Phil Turmel pturmel-webdev at turmel.org
Tue Mar 13 22:40:09 CDT 2007


Stephen Rider wrote:
> I ended up with this, which works great:
> 
> // Get array of CSS files for Style dropdown
> $arrStyles = array();
> if ($handle = opendir(dirname(__FILE__) . '/styles')) {
>     while (false !== ($file = readdir($handle))) {
> 	   if ($file != '.' && $file != '..' && substr($file,1) != '.') {
> 			$arrStyles[] = $file;
> 		}
>     }
>     closedir($handle);
> }
> 
> What I'm making is a plugin for WordPress, so I want it to be as  
> server-flexible as possible; thus no PHP5-only functions.  Otherwise  
> scandir() would have done the job  a lot more easily.
> 
Stephen,

One thing to watch out for: unordered filesystems.  ReiserFS in 
particular does not maintain its directories in any ordinary sorted 
order.  If you want the file names in order, follow the above code block 
with one of:

natcasesort( $arrStyles );  // My favorite for directories [1]
sort( $arrStyles );         // [2]
asort( $arrStyles );        // [3]

Hope this helps,

Phil

[1] http://www.php.net/manual/en/function.natcasesort.php
[2] http://www.php.net/manual/en/function.sort.php
[3] http://www.php.net/manual/en/function.asort.php



More information about the thelist mailing list