PHP: Some Ways to Scan a Directory

Posted on December 12, 2008, Filled under PHP,  Bookmark it

This is a list with some methods to retrieve the contents from a directory (folder). The following functions show both the files & the folders located in a specific directory.

scandir()

array scandir ( string $directory [, int $sorting_order [, resource $context]] )

This function only works in PHP5+. It returns an array of files and folders from the specified path. Here’s an usage example:

<?php
$dir    = '/some_files';
$files1 = scandir($dir); // sort in alphabetical order (Ascending)
$files2 = scandir($dir, 1); // sort in alphabetical order (Descending)

echo "<pre>"; print_r($files1); echo "</pre>";
echo "<pre>"; print_r($files2); echo "</pre>";
?>

The example above would result in something like:

Array
(
    [0] => .
    [1] => ..
    [2] => index.php
    [3] => text_file.txt
    [4] => images
)
Array
(
    [0] => images
    [1] => text_file.txt
    [2] => index.php
    [3] => ..
    [4] => .
)

opendir(), while() & readdir()

This is the classical way to scan a directory in PHP. It’s an altternative to scandir() if you are using PHP4. Example:

<?php
$dir = "/images";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}
>

To sort the resulted array you can use either sort() (elements will be arranged from lowest to highest) or rsort() (elements will be arranged from highest to lowest).

glob()

array glob ( string $pattern [, int $flags] )

This function finds pathnames matching a specific pattern. To get all files from a directory we’ll use *. It’s a convenient way to replace opendir() and friends ;-)

<?php
// get files from current directory
foreach (glob("*") as $filename) {
   echo $filename; echo "<br />";
}

// get files from 'images'
foreach (glob("images/*") as $filename) {
   echo $filename; echo "<br />";
}

// get files from 'documents' that end with .doc
foreach (glob("documents/*.doc") as $filename) {
   echo $filename; echo "<br />";
}
?>

The find out more about these functions, consider checking the PHP Documentation.

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Sponsors

4 Replies to "PHP: Some Ways to Scan a Directory"

  1. foreach (glob("images/*") as $filename) {
    echo $filename; echo "<br>";
    }

    It could be :

    foreach (glob("images/*") as $filename) {
    echo $filename."<br>";
    }

  2. Of course. I've focused on the 'scan directory' methods ;)

  3. On my real estate webisite I have trouble to get file name separate from extension.

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled