Working with Directories in PHP

In this tutorial, we will learn how to work with directories in PHP applications. Managing directories is an essential task for operations such as organizing file uploads, maintaining content hierarchies, and facilitating data storage solutions.

Whether you are building a file manager, content management system (CMS), e-commerce platform, or user file upload system in PHP, you will often need to create, read, update, and delete directories.

PHP provides several built-in directory functions that make these operations simple and efficient. Let’s begin by understanding: What is a directory?

What is a Directory in PHP?


A directory (also known as a folder) is a special type of file system container that stores files and other subdirectories in an organized structure. Directories help you to manage and arrange data logically within a project.

In PHP, directories are treated as special files, and you can work with them using PHP’s built-in directory functions. These functions allow you to perform essential operations, such as:

  • Create a directory for storing files or uploads.
  • Open and read directory contents to list files inside a folder.
  • Check if a directory exists before creating or deleting it.
  • Delete a directory when it’s no longer needed.
  • Change directory permissions to control access and security.

Real-time Examples of Directories in PHP


1. User File Uploads

When users upload any documents or images, PHP can automatically create a dedicated directory like:

uploads/user_101/
uploads/user_102/

This helps in keeping user data separate and organized.

2. Content Management Systems (CMS)

A CMS such as WordPress or Joomla stores images and media in structured directories based on date or category. For example:

/uploads/2025/09/

This structure makes content management more organized and efficient.

3. Log and Backup Folders

Web applications often store logs in a /logs/ directory and database backups in a /backups/ directory. For example:

/logs/error_log.txt
/backups/db_backup_2025.sql

These directories simplify application monitoring and recovery.

4. E-commerce Platforms

Online stores may create separate directories for product images, invoices, or customer records. For example:

/products/images/
/orders/invoices/

This approach ensures that product-related files and customer documents remain well-organized.

Directory Operations in PHP


Here are the most common directory operations that we often use in PHP:

  1. Create a directory → mkdir()
  2. Check if directory exists → is_dir(), file_exists()
  3. Open a directory → opendir()
  4. Read directory contents → readdir(), scandir()
  5. Get current working directory → getcwd()
  6. Change directory → chdir()
  7. Rename or move a directory → rename()
  8. Delete a directory → rmdir()
  9. Get path information → dirname(), realpath()
  10. Iterating recursively → RecursiveDirectoryIterator (OOPs approach)

Let’s explore each in detail with examples.

Creating a Directory in PHP


PHP provides a built-in mkdir() function, which is used to create a new directory. Its general syntax is:

mkdir(string $directory, int $permissions = 0777, bool $recursive = false);

The mkdir() function in PHP accepts three parameters:

  • $directory → The name or path of the directory to be created.
  • $permissions → The access permissions for the directory (default is 0777). 0755 is recommended for security.
  • $recursive → Set to true if you want to create nested (or multi-level) directories.

Example: Create a Directory

<?php
// Define the directory name we want to create.
$dir = "uploads";
// Check if the directory does not exist.
if (!is_dir($dir)) {
 // Create the directory with permission 0755.
    mkdir($dir, 0755);
  // Display the success message.
    echo "Directory '{$dir}' created successfully.";
} else {
  // Display an error message if the directory already exists.
    echo "Error creating directory '{$dir}'. Directory already exists.";
}
?>
Output:
      Directory 'uploads' created successfully.

In this example, the is_dir($dir) checks if a directory named uploads already exists. The ! (NOT operator) reverses the result:

  • If the folder does not exist, the condition is true, and the code inside runs.
  • If the folder exists, the condition is false, and the else block runs.


The mkdir($dir, 0755) function creates the new directory with the given permissions. 0755 means:

  • Owner → Read, Write, Execute
  • Group → Read, Execute
  • Others → Read, Execute

Checking If a Directory Exists


Before creating, renaming, or deleting a directory, you should always check if it already exists. PHP provides two built-in functions:

  • file_exists() function
  • is_dir() function

PHP file_exists() Function


The file_exists() function checks whether a file or directory exists at the given path. Its general syntax is as:

bool file_exists(string $path);

This function takes one parameter named $path, which represents the name of file or directory path you want to check. If the file or directory exists, then it returns true. Otherwise, it returns false.

Example: Checking if a Directory Exists

<?php
if (file_exists("uploads")) {
     echo "The directory exists.";
} else {
     echo "The directory does not exist.";
}
?>
Output:
      The directory exists.

PHP is_dir() Function Function


The is_dir() function is a built-in PHP function that checks whether the given path is specifically a directory. Its basic syntax is:

bool is_dir(string $path);

The is_dir() function accepts one parameter named $path that specifies the path you want to test. It returns true if the path is a directory, otherwise false.

Example 1: Checking a Directory

<?php
if (is_dir("uploads")) {
     echo "Yes, this is a directory.";
} else {
     echo "This is not a directory.";
}
?>
Output:
      Yes, this is a directory.

Opening and Reading Directory in PHP


PHP provides built-in functions to open and read the contents of directories. To open a directory in PHP, we use opendir() function. Its general syntax is as:

opendir(string $directory, ?resource $context = null): resource|false

The opendir() function takes a path to a directory as its argument and returns a directory handle (resource) on the success. Otherwise, it returns false on failure.

Once a directory is opened, you can use readdir() function to read its contents. It reads one entry at a time. Its basic syntax is as:

string|false readdir(resource $dir_handle);

The readdir() function accepts a directory handle obtained from opendir(). This function returns the name of the next file in the directory on each call. When all files have been read, the readdir() function returns false.

Example: Opening and Reading a Directory

<?php
$dir = "uploads"; // Name of directory.
// Check if the given path is actually a directory.
if (is_dir($dir)) {
 // Try to open the directory and get a handle (resource).
    if ($handle = opendir($dir)) {
        echo "Files inside $dir: \n";
     // Loop through the directory entries one by one.
        while (($file = readdir($handle)) !== false) {
        // Each iteration gives the name of a file or subdirectory.
           echo $file . "\n";
        }
     // Close the directory handle after finishing.
        closedir($handle);
   }
}
?>
Output:
      Files inside uploads:
      .
      ..
      image1.jpg
      notes.txt
      report.pdf

In this example, the opendir($dir) function opens the directory and returns a directory handle (resource). If the directory is opened, it allows us to read the directory contents.

We have used while loop to read all files and subdirectories inside a directory. The function readdir() reads the next entry (file or directory) from the directory handle $handle. Each time it is called, it moves to the next entry. When there are no more entries left, it returns false.

On the first call, the readdir($handle) reads the first entry and assigns it to $file. In other words, the return value of readdir($handle) is stored in the variable named $file. The loop checks if $file !== false. If it evaluates to true, it executes the loop body. On the second call, it will contain the next entry, and so on.

The loop repeats until there are no more entries left in the directory. The operator (!==) checks that $file is not exactly equal to false. This ensures the loop continues as long as readdir() successfully returns an entry. Once readdir() function returns false (i.e. no more files), the loop stops.

The closedir($handle) function closes the directory handle to free up resources once reading is finished.

Why “.” and “..” Always Appear?

When you read a directory in PHP, you’ll always see two special entries:

  • . (dot) → This refers to the current directory itself.
  • .. (double dot) → This refers to the parent directory (one level up).

These are system entries created by the file system, not actual files you uploaded. That’s why they always appear first when reading directories.

How to Skip “.” and “..”?

Since these are not useful when you are listing real files. You can check for them inside your loop and skip them using an if statement.

Example: Skipping . and ..

<?php
$dir = "uploads";
if ($handle = opendir($dir)) {
   echo "Files inside '$dir': \n";
   while (($file = readdir($handle)) !== false) {
   // Skip the special entries "." and "..".
      if ($file == "." || $file == "..") {
        continue;
      }
      echo $file . "\n";
   }
   closedir($handle);
}
?>
Output:
      Files inside 'uploads':
      image1.jpg
      notes.txt
      report.pdf

In this example, we have used an if condition with continue statement to skip current directory (.) and parent directory (..).

Note: The readdir() function does not read the contents of the files stored in a directory. It only lists the names of files and subdirectories inside an open directory. It does not open or read the actual contents of those files.

Conclusion

Working with directories in PHP is simple when you know the right functions. I hope that you have understood the how to create, read, and close directories easily with the help of examples. Stay tuned with the next tutorial where you will learn how to scan a directory in PHP.