0
0
PHPprogramming~5 mins

Directory operations in PHP

Choose your learning style9 modes available
Introduction

Directory operations help you work with folders on your computer using PHP. You can create, read, and list folders to organize files.

When you want to create a new folder to save files.
When you need to list all files inside a folder.
When you want to check if a folder exists before saving data.
When you want to delete an empty folder.
When you want to read folder contents to display on a website.
Syntax
PHP
<?php
// Open a directory
$dir = opendir('path/to/directory');

// Read entries
while (($file = readdir($dir)) !== false) {
    echo $file . "\n";
}

// Close directory
closedir($dir);

// Create a directory
mkdir('path/to/new_directory');

// Check if directory exists
if (is_dir('path/to/directory')) {
    // do something
}

// Remove a directory (must be empty)
rmdir('path/to/directory');
?>

Use opendir() to open a folder and readdir() to read its contents.

mkdir() creates a new folder, and rmdir() removes an empty folder.

Examples
This creates a new folder named my_folder in the current directory.
PHP
<?php
mkdir('my_folder');
?>
This checks if my_folder exists and prints a message.
PHP
<?php
if (is_dir('my_folder')) {
    echo "Folder exists.";
} else {
    echo "Folder does not exist.";
}
?>
This opens my_folder and lists all files and folders inside it.
PHP
<?php
$dir = opendir('my_folder');
while (($file = readdir($dir)) !== false) {
    echo $file . "\n";
}
closedir($dir);
?>
This removes the empty folder my_folder.
PHP
<?php
rmdir('my_folder');
?>
Sample Program

This program creates a folder, checks it, lists its contents (which are just special entries), then removes it and confirms removal.

PHP
<?php
// Create a folder named 'test_dir'
mkdir('test_dir');

// Check if folder exists
if (is_dir('test_dir')) {
    echo "Folder 'test_dir' created successfully.\n";
}

// Open the folder
$dir = opendir('test_dir');

// Since it's empty, reading will show '.' and '..'
while (($file = readdir($dir)) !== false) {
    echo "Found entry: $file\n";
}

// Close the directory
closedir($dir);

// Remove the folder
rmdir('test_dir');

// Confirm removal
if (!is_dir('test_dir')) {
    echo "Folder 'test_dir' removed successfully.";
}
?>
OutputSuccess
Important Notes

The entries '.' and '..' represent the current and parent directories and always appear when reading a directory.

You cannot remove a folder with rmdir() if it contains files or other folders.

Always close directories with closedir() after opening them.

Summary

Use mkdir() to create folders and rmdir() to remove empty folders.

Use opendir(), readdir(), and closedir() to read folder contents.

Check if a folder exists with is_dir() before working with it.