PHP Directory Functions

by Vincy. Last modified on July 3rd, 2022.

Some days before we have seen a set of basic PHP file functions to perform file open, read, write or append operations. Similarly, PHP includes a set of directory functions to deal with the operations, like, listing directory contents, and create/ open/ delete specified directory and etc. These basic functions are listed below.

  • mkdir(): To make new directory.
  • opendir(): To open directory.
  • readdir(): To read from a directory after opening it.
  • closedir(): To close directory with resource-id returned while opening.
  • rmdir(): To remove directory.

In this article, we have to discuss each of the above basic directory functions in PHP with their corresponding usage of these functions, possible parameters to be passed if any, with suitable examples.

Creating New Directory

For creating a new directory using PHP programming script, mkdir() function is used, and, the usage of this function is as follows.

<?php
mkdir($directory_path, $mode, $recursive_flag, $context);
?>

This function accepts four arguments as specified. Among them, the first argument is mandatory, whereas, the remaining set of arguments is optional.

  • $directory_path: By specifying either relative and absolute path, a new directory will be created in such location if any, otherwise, will return an error indicating that there are no such locations.
  • $mode: The mode parameter accepts octal values on which the accessibility of the newly created directory depends.
  • $recursive: This parameter is a flag and has values either true or false, that allow or refuse to create nested directories further.
  • $context: As similar as we have with PHP unlink() having a stream for specifying protocols and etc.

This function will return boolean data, that is, true on successful execution, false otherwise.

Listing Directory Content in PHP

For listing the contents of a directory, we require two of the above-listed PHP directory functions, these are, opendir() and readdir(). There are two steps in directory listing using the PHP program.

  • Step 1: Opening the directory.
  • Step 2: Reading content to be listed one by one using a PHP loop.

Step 1: Opening Directory Link

As its name, opendir() function is used to perform this step. And, it has two arguments, one is compulsory for specifying the path of the directory, and the other is optional, expecting stream context if any. The syntax will be,

<?php
opendir($directory_path, $context);
?>

Unlike PHP mkdir() returning boolean value, this function will return resource data as like as fopen(), mysql_query() and etc. After receiving the resource identifier returned by this function, then only we can progress with the subsequent steps to read, rewind, or close the required directory with the reference of this resource id.

Otherwise, a PHP error will occur for indicating to the user, that the resource id is not valid.

Step 2: Reading Directory Content

For performing this step, we need to call readdir() function recursively until the directory handle reaches the end of the directory. For that, we need to specify the resource-id returned while invoking opendir(), indicated as directory handle.

PHP readdir() will return string data on each iteration of the loop, and this string will be the name of each item stored in the directory with its corresponding extension. For example,

<?php
$directory_handle = opendir($directory_path);
while ($directory_item = readdir($directory_handle)) {
    echo $directory_item . "<br>";
}
?>

And, thereby executing the above code sample, we can list the content of a directory as expected.

Closing Directory Link

Once the directory link is opened to perform a set of dependent operations like reading directory content, we need to close this link after completing the related functionalities required. For example,

<?php
$directory_handle = opendir($directory_path);
...
...
closedir($directory_handle);
?>

Removing Directory

We have seen in the previous article about how to delete a file from a directory using PHP unlink(). Similarly, for removing the entire directory, PHP provides a function named as rmdir() which accepts the same set of arguments, as mkdir(). These are, the $directory_path and $context(Optional) as stated below.

<?php
rmdir($directory_path, $mode, $recursive_flag, $context);
?>

But, this function will remove the directory, if and only if it is empty. For removing the non-empty directory, we need to create a user define function that recursively calls unlink() function to remove each file stored in the directory to be deleted.

Example: PHP Directory Functions:

The following PHP program deals with the set of directory functions, that is, for creating a new directory, opening and reading for listing directory content and closing the directory as follows.

<?php
mkdir("php_directory_functions_manual", 0777);
/* Creating files into php_directory_functions_manual */
$file_pointer1 = fopen("php_directory_functions_manual/mkdir.txt", "x");
$file_pointer2 = fopen("php_directory_functions_manual/rmdir.txt", "x");
fclose($file_pointer1);
fclose($file_pointer2);
$directory_handle = opendir("php_directory_functions_manual");
while ($directory_item = readdir($directory_handle)) {
    echo $directory_item . "<br>";
}
closedir($directory_handle);
?>

This program will return the list of created files by using fopen() function as shown below.

.
..
mkdir.txt
rmdir.txt

And then, let us have another example, for looking into how a directory can be removed.

<?php
$directory_handle = opendir("php_directory_functions_manual");
while ($directory_item = readdir($directory_handle)) {
    @unlink("php_directory_functions_manual/" . $directory_item);
}
closedir($directory_handle);
rmdir("php_directory_functions_manual");
?>

On iterating with a loop for reading each item stored in the directory, the unlink() function is invoked to wipe out the directory before attempting to delete it. And then, rmdir() is used by referring to the name of the directory, to remove it.

Note:

  • If we invoked opendir() only once in a PHP program, its dependent functions, like, readdir(), closedir() and etc., will execute successfully, without specifying the directory handle resource, since, it refers to recently returned resource by default. Rather, if we have multiple resource data referring to various directory links, then we need to specify the directory handle appropriately.
  • For getting the successful execution of PHP unlink() and rmdir(), all required permissions should be provided with the entries on which these functions are applied.
Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page