English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP Directory Parsing

In this tutorial, you will learn how to use PHP to handle directories or folders.

Using directories in PHP

In the previous chapter, you learned how to use files in PHP. Similarly, PHP also allows you to use directories on the file system, for example, you can open directories and read their contents, create or delete directories, list all files in the directory, and so on.

Create a new directory

You can create a new empty directory by calling the PHP mkdir() function with the path and name of the directory to be created, as shown in the following example:

<?php
//Directory path
$dir = "testdir"
 
// Check if the directory exists
if(!file_exists($dir)){
    //Attempt to create directory
    if(mkdir($dir)){
        echo "Directory creation successful.";
    } else {
        echo "Error: Unable to create directory.";
    }
} else {
    echo "Error: Directory already exists.";
}
?>

To make the mkdir() function work, the parent directory of the directory path specified in the parameter must already exist, for example, if you specify the directory path testdir/subdir than testdir PHP will produce an error in other ways.

Copy a file from one location to another

You can copy a file from one location to another by calling the PHP copy() function and passing the source path and target path as parameters. If the target file already exists, it will be overwritten. This is an example of creating a copy of the "example.txt" file in the backup folder.

<?php
//Source file path
$file = "example.txt"
 
//Target file path
$newfile = "backup"/example.txt"
 
// Check if the file exists
if(file_exists($file)){
    //Attempt to copy the file
    if(copy($file, $newfile)){
        echo "File copy successful.";
    } else {
        echo "Error: Unable to copy file.";
    }
} else {
    echo "Error: File does not exist.";
}
?>

To make this example work, it must already existBackupThe target directory and source file "example.txt". Otherwise, PHP will produce an error.

List all files in the directory

You can use the PHP scandir() function to list files and directories within a specified path.

Now, we will create a custom function that will use PHP recursion to list all files in the directory. This script will be very helpful if you are using a deeply nested directory structure.

<?php
//Define a function to output the files in the directory
function outputFile($path){
    //Check if the directory exists
    if(file_exists($path) && is_dir($path)){
        //Scan the files in this directory
        $result = scandir($path);
        
        // Filter out the current (.) and parent directory (..)
        $files = array_diff($result, array('.', '..'));
        
        if(count($files) > 0){
            //Loop through the resynchronized array
            foreach($files as $file){
                if(is_file("$path/$file")){
                    //Display the file name
                    echo $file . "<br>";
                } else if(is_dir("$path/$file")){
                    //If the directory is found, recursively call this function
                    outputFiles("$path/$file");
                }
            }
        } else {
            echo "Error: The file cannot be found in the directory.";
        }
    } else {
        echo "Error: The directory does not exist.";
    }
}
 
//Call the function
outputFiles("mydir");
?>		

List all files of a certain type

When dealing with directory and file structures, you may need to find certain types of files in the directory, such as listing only .text files or .png files, etc. You can easily do this with the PHP glob() function, which matches files based on patterns.

The following PHP code example will search documents List directories and all files with the .text extension. It will not search subdirectories.

<?php
/* Search the directory and loop through it, returning an array containing matching files */
foreach(glob("documents/*.txt") as $file){
    echo basename($file) . " (size: " . filesize($file) . " bytes)" . "<br>";
}
?>

The glob() function can also be used to find all files in a directory or its subdirectories. The function defined in the following example will recursively list all files in the directory, just like we used the scandir() function in the previous example.

<?php
//Define a function to output files in the directory
function outputFile($path){
    //Check if the directory exists
    if(file_exists($path) && is_dir($path)){
        // Search for files in the directory
        $files = glob($path ."/*);
        if(count($files) > 0){
            //Traverse the rearranged array
            foreach($files as $file){
                if(is_file("$file")){
                    //Only display the file name
                    echo basename($file) . "<br>";
                } else if(is_dir("$file")){
                    //If the directory is found, recursively call this function
                    outputFiles("$file");
                }
            }
        } else {
            echo "Error: The file type cannot be found in the directory.";
        }
    } else {
        echo "Error: The directory does not exist.";
    }
}
 
//Call the function
outputFiles("mydir");
?>