PHP Directory

Summary: in this tutorial, you will learn how to work with directories using various built-in functions in PHP.

Basic directory operations

PHP provides a set of handy functions that allow you to work with directories effectively. To manage a directory, you need to get a directory handle.

To get the directory handle of a directory, you pass the directory path to the opendir() function as follows:

<?php

$dh = opendir('./public');Code language: HTML, XML (xml)

If an error occurs while opening the directory, the opendir() function returns false.

When you’re done with the directory, you need to close the directory handle by using the closedir() function:

<?php

closedir($dh);Code language: HTML, XML (xml)

Each directory may contain a list of files or sub-directories. It may also contain the dot entry (.) that represents the current directory and the entry (..) that represents the parent directory.

To get the next entry (a file or a directory) in a directory, you pass the directory handle to the readdir() function.

Suppose the public directory is as follows:

.
├── css
│   └── style.css
└── js
    └── app.jsCode language: CSS (css)

The following example lists all subdirectories in the public directory:

<?php

$dh = opendir('./public');

if ($dh) {
	while ($e = readdir($dh)) {
		if ($e !== '.' && $e !== '..') {
			echo $e , PHP_EOL;
		}
	}
}

closedir($dh);Code language: HTML, XML (xml)

Output:

css
js

Note that the readdir() function returns the directories and files of the current directory specified by the directory handle. It doesn’t recursively returns the files and directories of the subdirectories.

The following code is functionally equivalent to the above example except that it uses the try...catch...finally statement to handle the error:

try {
	$dh = opendir('./public');
	if (!$dh) {
		throw new Exception('Error openning the directory');
	}
	while ($e = readdir($dh)) {
		if ($e !== '.' && $e !== '..') {
			echo $e . '<br>';
		}
	}
} catch (\Throwable $e) {
	echo $e->getMessage();
} finally {
	if ($dh) {
		closedir($dir);
	}
}Code language: PHP (php)

Get the current directory

By default, the current directory is the directory that contains the currently running script file. The current directory is important because it is used as the base directory for relative file paths.

To get the current directory, you use the getcwd() function:

<?php

echo getcwd();Code language: HTML, XML (xml)

To change the current directory to a new one, you use the chdir() function:

<?php

chdir('./dev');
echo getcwd();Code language: HTML, XML (xml)

After calling the chdir() function, the current directory changes to ‘./dev’. And you can verify it by calling the getcwd() function.

Create a new directory

To create a directory, you use the mkdir() function by passing the directory path. The mkdir() function returns true if it created the directory successfully of false otherwise.

<?php

$dir = './public/img';

if (mkdir($dir)) {
	echo ' The dir ', $dir, 'created successfully!';
}Code language: HTML, XML (xml)

Notice that the parent directory public must exist.

By default the mkdir() function sets 0777 to the new directory. If you want to set different a permission, you can pass it to the mkdir() function or use the chmod() function. For example:

<?php

$dir = './public/assets';
mkdir($dir, 0644);Code language: HTML, XML (xml)

For more information on setting permissions on the file or directory, check it out the file permissions tutorial.

Delete a directory

To delete a directory, you use the rmdir() function. And you need to have sufficient permissions to remove the directory.

Also, the directory needs to be empty. In other words, it doesn’t contain any files or sub-directories.

The following example deletes the directory assets under the public directory:

<?php

rmdir('./public/assets');Code language: HTML, XML (xml)

Check if a path is a directory

To check if a path is a directory, you use the is_dir() function:

is_dir ( string $filename ) : boolCode language: PHP (php)

The is_dir() function returns true if the $filename exists and is a directory. For example:

<?php

$path = './public';

if (is_dir($path)) {
	echo $path, ' is a directory.';
}Code language: HTML, XML (xml)

Summary

  • Use the opendir() function to open a directory and get the directory handle and the closedir() function once you are done with the directory.
  • Use the readdir() function to read the entries in a directory specified by a directory handle.
  • Use the mkdir() function to create a new directory.
  • Use the rmdir() function to remove a directory.
  • Use the is_dir() function to check if a path is a directory and that directory exists in the file system.
Did you find this tutorial useful?