Home » PHP Create a Directory : A Tutorial with Examples

PHP Create a Directory : A Tutorial with Examples

In PHP, creating directories is a common task when working with file systems, especially in applications that require uploading files, storing logs, organizing data, or dynamically creating folder structures.

PHP provides built-in functions such as mkdir() for creating directories programmatically.

In this tutorial, we will cover:

Let’s dive into each of these concepts with examples and explanations.

1. Creating a Directory with mkdir()

The mkdir() function in PHP is used to create a directory. It creates a single directory at the specified path.

Syntax:

mkdir(directory_path, permissions, recursive);
  • directory_path: The path to the directory you want to create.
  • permissions: Optional. The permissions to set for the directory (defaults to 0777).
  • recursive: Optional. If set to true, it will create all nested directories along the path.

Example (Creating a Simple Directory):

<?php
$directory = "example_directory";

// Create the directory
if (mkdir($directory)) {
    echo "Directory created successfully: $directory\n";
} else {
    echo "Failed to create directory: $directory\n";
}
?>
  • In this example, mkdir() creates the directory example_directory in the current directory. If the directory is created successfully, it prints a success message.

2. Setting Permissions When Creating a Directory

You can specify the permissions for the directory using the second parameter of mkdir(). The permission is represented as an octal number (e.g., 0755 for read and execute access for everyone, but write access only for the owner).

Example (Creating a Directory with Specific Permissions):

<?php
$directory = "secure_directory";
$permissions = 0755;  // Read and execute access for all, write access only for owner

// Create the directory with specific permissions
if (mkdir($directory, $permissions)) {
    echo "Directory created successfully with permissions: $permissions\n";
} else {
    echo "Failed to create directory: $directory\n";
}
?>
  • In this example, the directory secure_directory is created with permissions set to 0755. The owner of the directory can read, write, and execute, while others can only read and execute.

3. Creating Nested Directories

Sometimes, you may need to create a directory structure where multiple directories do not exist yet. The recursive parameter of mkdir() allows you to create nested directories in one step.

Example (Creating Nested Directories):

<?php
$nested_directories = "parent_directory/child_directory/sub_directory";

// Create the nested directories
if (mkdir($nested_directories, 0777, true)) {
    echo "Nested directories created successfully: $nested_directories\n";
} else {
    echo "Failed to create nested directories.\n";
}
?>
  • In this example, mkdir() creates the parent_directory, child_directory, and sub_directory in one call, thanks to the recursive parameter being set to true.

4. Checking If a Directory Exists

Before creating a directory, it’s often a good practice to check if the directory already exists to avoid errors. PHP provides the is_dir() function to check whether a directory exists.

Example (Checking If a Directory Exists):

<?php
$directory = "example_directory";

if (is_dir($directory)) {
    echo "The directory already exists: $directory\n";
} else {
    if (mkdir($directory)) {
        echo "Directory created successfully: $directory\n";
    } else {
        echo "Failed to create directory.\n";
    }
}
?>
  • In this example, the script first checks whether example_directory exists using is_dir(). If it doesn’t, it creates the directory.

5. Error Handling for Directory Creation

You can handle errors when creating directories by checking the return value of mkdir(). If mkdir() fails, it returns false, and you can output an error message or handle the error in another way.

Example (Error Handling for Directory Creation):

<?php
$directory = "protected_directory";

// Suppress errors using @ and handle them manually
if (@mkdir($directory) === false) {
    echo "Error: Failed to create directory. Check permissions or file path.\n";
} else {
    echo "Directory created successfully: $directory\n";
}
?>
  • In this example, the @ operator is used to suppress the error generated by mkdir(). We then check the result of the function call and output an error message if the directory creation fails.

6. Deleting a Directory with rmdir()

The rmdir() function is used to delete an empty directory. If the directory contains files or subdirectories, you must delete them first before removing the directory.

Syntax:

rmdir(directory_path);

Example (Deleting a Directory):

<?php
$directory = "example_directory";

// Delete the directory if it exists and is empty
if (is_dir($directory)) {
    if (rmdir($directory)) {
        echo "Directory deleted successfully: $directory\n";
    } else {
        echo "Failed to delete directory: $directory\n";
    }
} else {
    echo "Directory does not exist: $directory\n";
}
?>
  • In this example, rmdir() deletes example_directory if it exists and is empty. If the directory is not empty, the deletion will fail.

7. Example Use Case: Creating a Directory for File Uploads

Let’s consider a real-world use case where a directory is dynamically created to store uploaded files. The directory is created only if it doesn’t already exist.

Example (Creating a Directory for File Uploads):

<?php
$upload_directory = "uploads";

// Check if the uploads directory exists
if (!is_dir($upload_directory)) {
    // Create the uploads directory
    if (mkdir($upload_directory, 0777, true)) {
        echo "Uploads directory created: $upload_directory\n";
    } else {
        echo "Failed to create uploads directory.\n";
    }
} else {
    echo "Uploads directory already exists: $upload_directory\n";
}

// Simulate file upload
$file_name = "example_file.txt";
$file_path = $upload_directory . "/" . $file_name;
file_put_contents($file_path, "This is a test file.");

// Verify that the file was saved
if (file_exists($file_path)) {
    echo "File uploaded successfully: $file_path\n";
} else {
    echo "Failed to upload file.\n";
}
?>
  • In this example, the script checks if the uploads directory exists. If not, it creates the directory and then simulates a file upload by saving a test file (example_file.txt) in the newly created directory.

Output:

Uploads directory created: uploads
File uploaded successfully: uploads/example_file.txt
  • If the directory already exists, it skips the creation step and proceeds to save the file.

Summary of PHP Directory Functions:

Function Description
mkdir() Creates a directory.
is_dir() Checks if a directory exists.
rmdir() Deletes an empty directory.
file_exists() Checks if a file or directory exists.
chmod() Changes the permissions of a file or directory.

Conclusion

Creating directories dynamically in PHP is a common requirement in many web applications, such as when uploading files, generating logs, or organizing data.

In this tutorial, we covered:

  • How to create a directory using mkdir().
  • How to set permissions for directories.
  • How to create nested directories using the recursive parameter.
  • How to check whether a directory exists using is_dir().
  • Handling errors during directory creation.
  • How to delete a directory using rmdir().

You may also like