Skip to content

Working with directories

PHP provides several functions for working with directories, including creating, deleting, reading, and manipulating directories. Let’s go through these directory-related functions and see examples of how to use each one.

1. Creating a Directory

To create a new directory, use the mkdir() function.

Syntax:

php

Copy code

mkdir(path, mode, recursive);

  • path: The path to the directory you want to create.
  • mode: (Optional) Sets permissions, default is 0777 (readable, writable, executable by everyone).
  • recursive: (Optional) If set to TRUE, allows the creation of nested directories (e.g., “parent/child/grandchild”).

Example:

php

Copy code

<?php

$directory = “new_folder”;

if (mkdir($directory, 0777, true)) {

    echo “Directory created successfully.”;

} else {

    echo “Failed to create directory.”;

}

?>

2. Removing a Directory

To delete an empty directory, use the rmdir() function.

Syntax:

php

Copy code

rmdir(path);

  • path: The path to the directory to be deleted.

Note: rmdir() only works on empty directories. To delete a non-empty directory, you’ll need to delete each file within it first.

Example:

php

Copy code

<?php

$directory = “new_folder”;

if (rmdir($directory)) {

    echo “Directory deleted successfully.”;

} else {

    echo “Failed to delete directory.”;

}

?>

3. Reading the Contents of a Directory

To read files and directories within a directory, use scandir() or opendir() with readdir().

Using scandir()

The scandir() function returns an array of files and directories within a specified directory.

php

Copy code

<?php

$directory = “my_folder”;

$files = scandir($directory);

foreach ($files as $file) {

    if ($file !== “.” && $file !== “..”) {

        echo $file . “<br>”;

    }

}

?>

Using opendir() and readdir()

opendir() opens a directory handle, which you can read with readdir().

php

Copy code

<?php

$directory = “my_folder”;

if ($handle = opendir($directory)) {

    while (($file = readdir($handle)) !== false) {

        if ($file !== “.” && $file !== “..”) {

            echo $file . “<br>”;

        }

    }

    closedir($handle);

} else {

    echo “Failed to open directory.”;

}

?>

4. Checking if a Directory Exists

You can use is_dir() to check if a directory exists.

php

Copy code

<?php

$directory = “my_folder”;

if (is_dir($directory)) {

    echo “Directory exists.”;

} else {

    echo “Directory does not exist.”;

}

?>

5. Deleting All Files in a Directory

To delete all files in a directory, you can use a combination of glob() and unlink().

php

Copy code

<?php

$directory = “my_folder”;

foreach (glob(“$directory/*”) as $file) {

    if (is_file($file)) {

        unlink($file);

    }

}

echo “All files deleted from directory.”;

?>

Note: This only deletes files, not subdirectories. To delete everything within a directory, including subdirectories, you’d need a recursive approach.

6. Recursive Deletion of a Directory and its Contents

To delete a directory along with its contents, including subdirectories and files, you can create a recursive function.

php

Copy code

<?php

function deleteDirectory($directory) {

    if (!is_dir($directory)) return;

    $files = scandir($directory);

    foreach ($files as $file) {

        if ($file !== ‘.’ && $file !== ‘..’) {

            $filePath = $directory . DIRECTORY_SEPARATOR . $file;

            if (is_dir($filePath)) {

                deleteDirectory($filePath);

            } else {

                unlink($filePath);

            }

        }

    }

    rmdir($directory);

}

// Usage

$directory = “my_folder”;

deleteDirectory($directory);

echo “Directory and all contents deleted.”;

?>

7. Getting Directory Information

To get information about a directory, such as its size, you can write a custom function:

php

Copy code

<?php

function getDirectorySize($directory) {

    $size = 0;

    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {

        $size += $file->getSize();

    }

    return $size;

}

$directory = “my_folder”;

echo “Directory size: ” . getDirectorySize($directory) . ” bytes”;

?>

8. Changing the Current Directory

To change the current working directory in PHP, use chdir().

php

Copy code

<?php

$directory = “my_folder”;

if (chdir($directory)) {

    echo “Changed to directory: ” . getcwd();

} else {

    echo “Failed to change directory.”;

}

?>

Summary of Directory Functions in PHP

  • mkdir(): Creates a new directory.
  • rmdir(): Deletes an empty directory.
  • scandir(): Returns an array of files and directories inside a directory.
  • opendir() and readdir(): Opens and reads a directory handle.
  • is_dir(): Checks if a directory exists.
  • unlink(): Deletes a file (used within directories to delete all contents).
  • glob(): Retrieves file paths using patterns, useful for deleting or listing files.
  • chdir(): Changes the current directory.
  • Recursive directory functions: To delete or calculate the size of directories, especially if they contain files and subdirectories.