PHP Tutorials: Directory Handling

In the previous tutorial we have seen that how we can handle files. In this tutorial we will see how we can handle the directories. We will see that how we can list directories, create a directory, and delete a directory etc.

Create a Directory

Create a director in the server we can use mkdir(). The mkdir() function has 1 parameter which has full path to the location where you wanted to create the directory and the directory name.

Let us take an example and see how mkdir() works.

<?php
// The directory path
$direcotry_path = "www/html/demo";
 
// Check the existence of directory
if( !file_exists($direcotry_path) ){
    // Attempt to create directory
    if(mkdir($direcotry_path)){
        echo "SUCCESS: Directory $direcotry_path created successfully.";
    } else{
        echo "ERROR: Directory $direcotry_path could not be created.";
    }
} else{
    echo "ERROR: Directory $direcotry_path already exists.";
}
?>

file_exists() is to make sure if the directory or file exists already. If we accidentally create a directory which does already exists, then mkdir() can replace all the content that stay inside the directory. Always put a check before you create a directory and thats a good practice.

Copy Files

In PHP you can copy files from one location and move them to another location without affecting the original files. Please note that the copy function will not move the original files to the destination, but just it will create a replica of the files in the destination directory.

copy() function is used to perform the action. The copy() takes 2 parameters. the first is source and second is the destination. The source is the file you wanted to copy and destination is the location you wanted the file to copy.

Let us take an example

<?php
// Source
$source = "demo.php";
 
// Destination
$destination = "www/html/demo/demo.php";
 
// Check the existence of file
if(file_exists($file)){
    // Attempt to copy file
    if(copy($source, $destination)){
        echo "SUCCESS: File copied successfully.";
    } else{
        echo "ERROR: File could not be copied.";
    }
} else{
    echo "ERROR: File does not exist.";
}
?>

List all files in the Directory

PHP you can list all the files inside a directory. The scandir() function is used for this purpose. The scandir() function accepts one parameter and that is the path of the directory that you wanted to parse. It is this similar to the dir command in MSDOS and ls command in Linux.

Let us take an example and see how scandir() function works.

<?php
$directory_path = "www/html/demo";
// Check directory exists or not
if(file_exists($directory_path) && is_dir($directory_path)){
    // Scan the files in this directory
    $result = scandir($directory_path);
    
    // Filter out the current (.) and parent (..) directories
    $file_list = array_diff($result, array('.', '..'));
    
    if(count($file_list) > 0){
        // Loop through retuned array
        foreach($file_list as $key => $file){
            if(is_file("$directory_path/$file")){
                // Display filename
                echo $file . "<br>";
            } else if(is_dir("$directory_path/$file")){
                // Recursively call the function if directories found
                outputFiles("$directory_path/$file");
            }
        }
    } else{
        echo "ERROR: No files found in the directory.";
    }
} else {
    echo "ERROR: The directory does not exist.";
}
?>

List files of a certain extension

There will be some situations when you will need to list all the files of a certain extension. The extensions can be .png, .txt, .jpg etc. To do this PHP as a function called glob(). The glob() function matches files based on extension.

Let us see an example of glob().

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

The glob() function can also be used to list all the files inside a directory and it’s sub directories. To do this we have to use a function recursively which will call itself again and again till the time it reaches the Last child of the directory. I’m sure you are confused with the term recursive at this point. Click here to know more about a recursive function.

<?php
// Define a function to output files in a directory
function listFiles($path){
    // Check directory exists or not
    if(file_exists($path) && is_dir($path)){
        // Search the files in this directory
        $files = glob($path ."/*");
        if(count($files) > 0){
            // Loop through retuned array
            foreach($files as $file){
                if(is_file("$file")){
                    // Display only filename
                    echo basename($file) . "<br>";
                } else if(is_dir("$file")){
                    // Recursively call the function if directories found
                    outputFiles("$file");
                }
            }
        } else{
            echo "ERROR: No such file found in the directory.";
        }
    } else {
        echo "ERROR: The directory does not exist.";
    }
}
 
// Call the function
listFiles("www/html/demo");
?>

Leave a Reply

Your email address will not be published. Required fields are marked *