Métodos de leer el contenido de un directorio con PHP

Reading through a directory with PHP

Posted June 18th, 2009 in PHP

PHP’s opendir() readdir() and closedir() are used for reading the contents of a directory (there’s also glob() and scandir() but I’ll cover those in later posts). Combined with functions like is_file() is_dir() and is_link() and you can easily build up a directory tree or process files etc.

Example directory

The examples below look at a directory with the following:

bar.txt       A regular file
baz           A directory
foo.txt       A regular file
link2foo.txt  A symbolic link to foo.txt

Simple example

A simple example to loop through the directory’s contents and display the names of the files, directories etc within it is as follows:

$handle = opendir("/path/to/directory");
while($name = readdir($handle)) {
    echo "$name\n";
}
closedir($handle);

The output for the example directory is:

foo.txt
..
bar.txt
.
baz
link2foo.txt

Note that it’s not sorted in any particular way and includes . and .. which are indicators for the current directory and parent directory.

Sorting the data

Instead of echoing out the filenames they could instead be stored in an array, sorted and then some other processing done on them. This will ensure they are in alphabetical order.

$handle = opendir("/path/to/directory");
$names = array();
while($name = readdir($handle)) {
    $names[] = $name;
}
closedir($handle);
sort($names);

Doing print_r($names) will show this:

Array
(
    [0] => .
    [1] => ..
    [2] => bar.txt
    [3] => baz
    [4] => foo.txt
    [5] => link2foo.txt
)

Testing what type of file it is

The final example loops through the directory and checks whether it’s a file, directory or symbolic link and does some processing depending on which type it is (in this example it’s simply echoing out what type it is and the name). The additional if($name != ‘.’ && $name != ‘..’) text excludes the special . and .. directory names.

$dir = "/path/to/dir";
$handle = opendir($dir);
while($name = readdir($handle)) {
    if(is_dir("$dir/$name")) {
        if($name != '.' && $name != '..') {
            echo "directory: $name\n";
        }
    }
    elseif(is_link("$dir/$name")) {
        echo "link: $name\n";
    }
    else {
        echo "file: $name\n";
    }
}
closedir($handle);

And the output:

file: foo.txt
file: bar.txt
directory: baz
link: link2foo.txt

Next posts in this series

To follow up this post I’ll look at using scandir() and glob().

Using PHP’s glob() function to find files in a directory

A couple of weeks ago I posted how to read through a directory with PHP using the opendir() readdir() and closedir() functions and now look at the glob() function. glob() returns the filenames into an array and supports pattern matching so it can be very easy to find e.g. jpg images in a particular directory.

Example directory

The examples below look at a directory with the following, the same example directory as used in the read through directory post:

bar.txt       A regular file
baz           A directory
foo.txt       A regular file
link2foo.txt  A symbolic link to foo.txt

Simple example

To find all the files in the directory /path/to/directory with a .txt file extension, you can do this:

$files = glob("/path/to/directory/*.txt");

The $files array contains the following from the example directory:

Array
(
    [0] => /path/to/directory/bar.txt
    [1] => /path/to/directory/foo.txt
    [2] => /path/to/directory/link2foo.txt
)

If no files matched the pattern then the array will be empty.

Example using braces

There are flags which can be passed as a second optional parameter. One of these is GLOB_BRACE which means that e.g. {jpg,gif,png} will be expanded to match jpg, gif and png which can be useful if you need to look for a particular set of files by their extension, in this example for image files.

If the example directory also had the files 1.jpg, 2.gif and 3.png then you can do this to get glob to return just the image files:

$files = glob("/path/to/directory/*.{jpg,gif,png}", GLOB_BRACE);

print_r($files) would echo:

Array
(
    [0] => /path/to/directory/1.jpg
    [1] => /path/to/directory/2.gif
    [2] => /path/to/directory/3.png
)

Further reading

This serves as an introduction to using glob() to find files with PHP. Read the glob manual page for more details and for information about the other flags.

Related posts:

There’s a lot of ways. The older way is scandir but DirectoryIterator is probably the best way.

There’s also readdir (to be used with opendir) and glob.

Here are some examples on how to use each one to print all the files in the current directory:

DirectoryIterator usage: (recommended)

foreach (new DirectoryIterator(‘.’) as $file) {

if($file->isDot()) continue;

print $file->getFilename() . ‘
‘;

}

scandir usage:

$files = scandir(‘.’);

foreach($files as $file) {

if($file == ‘.’ || $file == ‘..’) continue;

print $file . ‘
‘;

}

opendir and readdir usage:

if ($handle = opendir(‘.’)) {

while (false !== ($file = readdir($handle))) {

if($file == ‘.’ || $file == ‘..’) continue;

print $file . ‘
‘;

}

closedir($handle);

}

glob usage:

foreach (glob(“*”) as $file) {

if($file == ‘.’ || $file == ‘..’) continue;

print $file . ‘
‘;

}

As mentioned in the comments, glob is nice because the asterisk I used there can actually be used to do matches on the files, so glob(‘*.txt’) would get you all the text files in the folder and glob(‘image_*’) would get you all files that start with image_

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s