PHP Directory Handling
Files are organized into directories, also called folders. This article describes how to create and remove directories and how to get a list of the files in a directory.
1. Create Directory
To create a directory, use the mkdir function, as follows:
mkdir('testdir');
This statement creates a new directory named testdir in the same directory where the script is located. If a directory already exists with the same name, a warning is displayed and the new directory is not created.
You can check first to see whether the directory already exists by using the following statements:
if (!is_dir('mynewdir;))
{
mkdir('mynewdir');
}
else
{
echo 'Directory already exists!';
}
2. List of Files in a Directory
Getting a list of the files in a directory is often useful. For example, you might want to provide a list of files for users to download or want to display images from files in a specific directory.
PHP provides functions for opening and reading directories. To open a directory, use the opendir() function, as follows:
$dh = opendir('/topdir/testdir);
If you attempt to open a directory that doesn't exist, a warning is displayed.
The closedir() function closes the directory stream.
The variable $dh is a directory handle, a pointer to the open directory that you can use later to read from the directory. To read a filename from the directory, use the readdir() function, as follows:
$filename = readdir($dh);
After this statement, $filename contains the name of a file. Only the filename is stored in $filename, not the entire path to the file. To read all the filenames in a directory, you can use a while loop, as follows:
while ($filename = readdir($dh))
{
echo $filename . "\n";
}
The readdir() also returns the . and .. entries common to a Unix directory listing. You can easily filter these out with an if statement:
if ($file != '.' && $file != '..')
{
}
The readdir() function doesn’t provide any control over the order in which filenames are read, so you don’t always get the filenames in the order you expect.
3. Reading Directory into an Array
The scandir() function returns an array consisting of files and directories found in directory or returns FALSE on error.