Directory Handling and File Management in PHP Practice Questions with Solutions

Introduction

Directory handling in PHP allows you to create, open, read, rename, and delete folders. File management helps you organize files, check their details, move them, and manage their storage. These concepts are useful when building document management systems, student record applications, and file upload projects. In this chapter, you will practise Directory Handling and File Management in PHP these operations through practical PHP examples.

Question 1: Create a Directory Using PHP

Problem Statement:
Write a PHP program to create a directory named students if it does not already exist.

PHP Solution:

<?php

$folder = "students";

if (!is_dir($folder)) {

    if (mkdir($folder)) {
        echo "Directory created successfully.";
    } else {
        echo "Unable to create directory.";
    }

} else {

    echo "Directory already exists.";

}

?>

Sample Output:

Directory created successfully.

Explanation:

  • $folder stores the directory name.
  • is_dir() checks whether the directory exists.
  • mkdir() creates a new directory.
  • The program avoids creating the same directory again.

Concepts Covered: mkdir(), is_dir(), directory creation.


Question 2: Check Whether a Directory Exists

Problem Statement:
Write a PHP program to check whether a directory named students exists.

PHP Solution:

<?php

$folder = "students";

if (is_dir($folder)) {

    echo "Students directory exists.";

} else {

    echo "Students directory does not exist.";

}

?>

Sample Output:

Students directory exists.

Explanation:

  • is_dir() checks whether the specified path is an existing directory.
  • It returns true if the directory exists.
  • Otherwise, it returns false.
  • The if-else statement displays the appropriate message.

Concepts Covered: is_dir(), directory checking, conditional statements.


Question 3: Open and Read a Directory

Problem Statement:
Create a PHP program to open the students directory and display its file and folder names.

PHP Solution:

<?php

$folder = "students";

$directory = opendir($folder);

if ($directory) {

    echo "Directory Contents:\n";

    while (($item = readdir($directory)) !== false) {

        if ($item != "." && $item != "..") {
            echo $item . "\n";
        }

    }

    closedir($directory);

} else {

    echo "Unable to open directory.";

}

?>

Sample Output:

Directory Contents:
rahul.txt
priya.txt

The displayed names depend on the actual contents of your directory.

Explanation:

  • opendir() opens the specified directory.
  • readdir() reads one entry at a time.
  • . represents the current directory, and .. represents its parent directory.
  • These two entries are excluded from the output.
  • closedir() closes the directory handle.

Concepts Covered: opendir(), readdir(), closedir(), directory traversal.


Question 4: Create Multiple Directories at Once

Problem Statement:
Write a PHP program to create three directories named students, teachers, and courses.

PHP Solution:

<?php

$folders = ["students", "teachers", "courses"];

foreach ($folders as $folder) {

    if (!is_dir($folder)) {

        if (mkdir($folder)) {
            echo $folder . " directory created.\n";
        }

    } else {

        echo $folder . " directory already exists.\n";

    }

}

?>

Sample Output:

students directory created.
teachers directory created.
courses directory created.

Explanation:

  • The $folders array stores three directory names.
  • foreach processes each directory name.
  • is_dir() checks whether the directory already exists.
  • mkdir() creates directories that are missing.

Concepts Covered: Multiple directory creation, arrays, loops, mkdir().


Question 5: Rename a Directory

Problem Statement:
Write a PHP program to rename a directory from students to student_records.

PHP Solution:

<?php

$oldName = "students";
$newName = "student_records";

if (is_dir($oldName)) {

    if (rename($oldName, $newName)) {

        echo "Directory renamed successfully.";

    } else {

        echo "Unable to rename directory.";

    }

} else {

    echo "Original directory does not exist.";

}

?>

Sample Output:

Directory renamed successfully.

Explanation:

  • $oldName stores the existing directory name.
  • $newName stores the new directory name.
  • rename() changes the directory name.
  • The program checks whether the original directory exists before renaming it.

Concepts Covered: rename(), directory management, path checking.


Question 6: Find All Files Using glob()

Problem Statement:
Write a PHP program to display all text files available inside the student_records directory.

PHP Solution:

<?php

$files = glob("student_records/*.txt");

echo "Text Files:\n";

foreach ($files as $file) {

    echo basename($file) . "\n";

}

?>

Sample Output:

Text Files:
rahul.txt
priya.txt
amit.txt

The output depends on the text files present in the directory.

Explanation:

  • glob() searches for files matching a specified pattern.
  • student_records/*.txt selects text files from the directory.
  • foreach processes the matching file paths.
  • basename() displays only the file name instead of the complete path.

Concepts Covered: glob(), file searching, basename(), wildcard patterns.


Question 7: Copy Files into Another Directory

Problem Statement:
Write a PHP program to copy rahul.txt from the student_records directory into a backup directory.

PHP Solution:

<?php

$source = "student_records/rahul.txt";
$destination = "backup";

if (!is_dir($destination)) {
    mkdir($destination);
}

if (is_file($source)) {

    if (copy($source, $destination . "/rahul.txt")) {

        echo "File copied to backup directory.";

    } else {

        echo "File copying failed.";

    }

} else {

    echo "Source file does not exist.";

}

?>

Sample Output:

File copied to backup directory.

Explanation:

  • $source stores the original file path.
  • $destination stores the backup directory name.
  • mkdir() creates the backup directory if necessary.
  • is_file() checks whether the source is an existing file.
  • copy() copies the file into the backup directory.

Concepts Covered: copy(), is_file(), directory creation, file backup.


Question 8: Move a File into Another Directory

Problem Statement:
Write a PHP program to move priya.txt from the student_records directory into the backup directory.

PHP Solution:

<?php

$source = "student_records/priya.txt";
$destination = "backup/priya.txt";

if (is_file($source) && is_dir("backup")) {

    if (rename($source, $destination)) {

        echo "File moved successfully.";

    } else {

        echo "Unable to move file.";

    }

} else {

    echo "Source file or backup directory is missing.";

}

?>

Sample Output:

File moved successfully.

Explanation:

  • $source contains the original file path.
  • $destination contains the new file path.
  • rename() moves the file to the new location on the same filesystem.
  • The original file path is no longer available after a successful move.

Concepts Covered: File movement, rename(), is_file(), is_dir().


Question 9: Get File Information from a Directory

Problem Statement:
Write a PHP program to display the file name, file size, and file type of rahul.txt inside the student_records directory.

PHP Solution:

<?php

$file = "student_records/rahul.txt";

if (is_file($file)) {

    echo "File Name: " . basename($file) . "\n";

    echo "File Size: " . filesize($file) . " bytes\n";

    echo "File Type: " . filetype($file);

} else {

    echo "File does not exist.";

}

?>

Sample Output:

File Name: rahul.txt
File Size: 25 bytes
File Type: file

The file size depends on the actual content of rahul.txt.

Explanation:

  • is_file() checks whether the path points to a regular file.
  • basename() extracts the file name.
  • filesize() returns the file size in bytes.
  • filetype() identifies the type of filesystem entry.

Concepts Covered: basename(), filesize(), filetype(), file information.


Question 10: Build a Simple File Management System

Problem Statement:
Create a PHP program that creates a company_files directory, stores three employee records, displays all text files, and shows their file sizes.

PHP Solution:

<?php

$folder = "company_files";

if (!is_dir($folder)) {
    mkdir($folder);
}

$employees = [
    "rahul.txt" => "Rahul, Developer, 35000",
    "priya.txt" => "Priya, HR, 40000",
    "amit.txt" => "Amit, Sales, 30000"
];

foreach ($employees as $filename => $details) {

    file_put_contents($folder . "/" . $filename, $details);

}

echo "Employee Files:\n\n";

$files = glob($folder . "/*.txt");

foreach ($files as $file) {

    echo "File: " . basename($file) . "\n";

    echo "Size: " . filesize($file) . " bytes\n\n";

}

?>

Sample Output:

Employee Files:

File: rahul.txt
Size: 23 bytes

File: priya.txt
Size: 20 bytes

File: amit.txt
Size: 21 bytes

The output order and file sizes depend on the actual file names and content.

Explanation:

  • mkdir() creates the company directory if it does not exist.
  • The $employees associative array stores file names and employee details.
  • foreach writes each employee record into a separate text file.
  • glob() finds all text files in the directory.
  • basename() displays each file name.
  • filesize() displays the size of each employee file.

Concepts Covered: Directory creation, associative arrays, file writing, glob(), file information, file management.


Key Takeaways

  • mkdir() creates a new directory.
  • is_dir() checks whether a directory exists.
  • opendir() opens a directory.
  • readdir() reads directory entries.
  • closedir() closes an opened directory.
  • glob() searches for files matching a pattern.
  • rename() can rename or move files and directories.
  • copy() creates a duplicate of a file.
  • is_file() checks whether a path points to a regular file.
  • basename() extracts the file name from a path.
  • filesize() returns file size in bytes.
  • Always validate file paths and permissions before performing file operations.

FAQs: Directory Handling and File Management in PHP

1. What is directory handling in PHP?

Directory handling in PHP allows developers to create, open, read, rename, and manage folders using built-in functions.

2. Which function is used to create a directory in PHP?

The mkdir() function creates a new directory.

3. How can we check whether a directory exists?

Use the is_dir() function to check whether the specified path is an existing directory.

4. What is the purpose of opendir() in PHP?

opendir() opens a directory so that its entries can be read.

5. What is the difference between readdir() and glob()?

readdir() reads directory entries one at a time using an opened directory handle. glob() searches for files matching a specified pattern and returns matching paths as an array.

6. How can we rename a directory in PHP?

Use the rename() function with the existing directory path and the new directory path.

7. How can we copy a file into another directory?

Use the copy() function and provide the source file path and destination file path.

8. How can we move a file in PHP?

The rename() function can move a file to another location when the operation is supported by the filesystem. Moving across filesystems may require copying and then deleting the original.

9. How can we get the size of a file in PHP?

Use the filesize() function to get the size of a file in bytes.

10. What is the difference between is_file() and is_dir()?

is_file() checks whether a path points to a regular file, while is_dir() checks whether it points to a directory.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top