Chapter 25. Directories


A filesystem stores a lot of additional information about files aside from their actual contents. This information includes such particulars as the file size, directory, and access permissions. If you’re working with files, you may also need to manipulate this metadata. PHP gives you a variety of functions to read and manipulate directories, directory entries, and file attributes. Like other file-related parts of PHP, the functions are similar to the C functions that accomplish the same tasks, with some simplifications.

Files are organized with inodes. Each file (and other parts of the filesystem, such as directories, devices, and links) has its own inode. That inode contains a pointer to where the file’s data blocks are as well as all the metadata about the file. The data blocks for a directory hold the names of the files in that directory and the inode of each file.

PHP provides a few ways to look in a directory to see what files it holds. The Directory-Iterator class provides a comprehensive object-oriented interface for directory traversal. This example uses DirectoryIterator to print out the name of each file in a directory:

foreach (new DirectoryIterator('/usr/local/images') as $file) {
    print $file->getPathname() . "\n";

The opendir(), readdir(), and closedir() functions offer a procedural approach to the same task. Use opendir() to get a directory handle, readdir() to iterate through the files, and closedir() to close the directory handle. ...

Get PHP Cookbook, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.