Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Directory Operations in PHP

Introduction

Directory operations are essential for managing the file system in PHP. This tutorial will cover basic directory operations such as creating, reading, and deleting directories, as well as listing files within a directory. By understanding these operations, you can efficiently handle files and directories in your PHP projects.

Creating a Directory

To create a directory in PHP, you can use the mkdir() function. This function creates a new directory with the specified pathname.

Example: Creating a directory named "example_dir"

<?php
$dir = "example_dir";
if (!file_exists($dir)) {
    mkdir($dir, 0777, true);
    echo "Directory created successfully.";
} else {
    echo "Directory already exists.";
}
?>
                

Reading a Directory

To read the contents of a directory, you can use the opendir(), readdir(), and closedir() functions. These functions allow you to open a directory, read its contents, and then close the directory.

Example: Listing files in a directory

<?php
$dir = "example_dir";
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: " . $file . "<br>";
        }
        closedir($dh);
    }
} else {
    echo "Directory does not exist.";
}
?>
                

Deleting a Directory

To delete a directory, you can use the rmdir() function. Note that the directory must be empty before it can be deleted.

Example: Deleting a directory named "example_dir"

<?php
$dir = "example_dir";
if (is_dir($dir)) {
    if (rmdir($dir)) {
        echo "Directory deleted successfully.";
    } else {
        echo "Failed to delete directory. Make sure it is empty.";
    }
} else {
    echo "Directory does not exist.";
}
?>
                

Listing All Files in a Directory

To list all files and directories within a directory, you can use the scandir() function. This function returns an array of filenames.

Example: Listing all files and directories in "example_dir"

<?php
$dir = "example_dir";
if (is_dir($dir)) {
    $files = scandir($dir);
    foreach ($files as $file) {
        echo $file . "<br>";
    }
} else {
    echo "Directory does not exist.";
}
?>
                

Checking if a Directory Exists

To check if a directory exists, you can use the is_dir() function. This function returns true if the specified path is a directory, and false otherwise.

Example: Checking if "example_dir" exists

<?php
$dir = "example_dir";
if (is_dir($dir)) {
    echo "Directory exists.";
} else {
    echo "Directory does not exist.";
}
?>
                

Conclusion

In this tutorial, we covered the basic directory operations in PHP, including creating, reading, and deleting directories, as well as listing files within a directory. By mastering these operations, you can effectively manage files and directories in your PHP applications.