Categories
php

PHP Function to list contents of a directory

php function to list files & directories in a folder

Many times you need to get the list of contents of a directory in php scripts. You can get list of files and directories in a directory by using following function. It returns the list of items as an array.
[php]
function getdirlist($dir){

return array_diff( scandir( $dir ), Array( “.”, “..” ) );

}

[/php]
This function works in php5 environment only.

But if there are too many files in the folder you can use the below function to list each of them.

[php]

function getlist($directory){
$results = array();

// create a handler for the directory
//$directory=”.”;
$handler = opendir($directory);

// keep going until all files in directory have been read
while ($file = readdir($handler)) {

// if $file isn’t this directory or its parent,
// add it to the results array
if ($file != ‘.’ && $file != ‘..’){
$results[] = $file;
}
}
// tidy up: close the handler
closedir($handler);

return $results;

}

[/php]