PHP Parsing Directories


In PHP, you can work with directories.

You learned how to deal with files in PHP in the previous tutorial. Similarly, PHP allows you to deal with file system folders, such as opening a directory and reading its contents, creating and deleting directories, and listing all files in a directory, among other things.


How to Make a New Directory

By invoking the mkdir() path and directory name of PHP you can make a new empty directory, as shown below:


<?php
  // The directory path
  $dir = "testdir";

  // Check the existence of directory
  if(!file_exists($dir)){
  // Attempt to create directory
  if(mkdir($dir)){
    echo "Directory created successfully.";
  }
  else{
    echo "ERROR: This Directory could not create.";
  }
  }
  else{
    echo "ERROR: Directory already exists.";
  }
?>


The parent directories in the directory path parameter must exist in order for the mkdir() function to work. For example, if you define the directory path as testdir/subdir, the testdir must exist otherwise PHP would produce an error.


Transferring Files from One Place to Another

By passing the file's source and destination paths as arguments to the PHP copy() function, you can copy a file from one location to another. The destination file in this case shall be overwritten if it actually already exists. Here's an example of how to make a backup copy of the "example.txt" file.


<?php
  // Source file path
  $file = "example.txt";

  // Destination
  // file path
  $newfile = "backup/example.txt";

  // Check the
  // existence of file
  if(file_exists($file)){
  // Attempt to
  // copy file
  if(copy($file, $newfile)){
   echo "File copied successfully.";
  }
  else{
    echo "ERROR: File could not be copied.";
    }
  }
  else{
    echo "ERROR: File does not exist.";
  }
?>


To make this example function, both the backup directory and the source file, "example.txt" must already exist; otherwise, PHP will throw an error.


Getting the Lists of All the Files in a Directory

The PHP scandir() function can be used to display a list of files and directories within a given direction.

Now we'll use PHP to build a custom feature that lists all files in a directory recursively. If you're dealing with a deeply nested directory structure, this script can come in handy.


<?php
  // Define a function to output files in a directory
  function outputFiles($path){
  // Check directory exists or not
  if(file_exists($path) && is_dir($path)){
  // Scan the files in this directory
  $result = scandir($path);

  // Filter out the
  // current (.)
  // and parent (..) directories
  $files = array_diff($result, array('.', '..'));

  if(count($files) > 0){
  // Loop through
  // retuned array
  foreach($files as $file){
  if(is_file("$path/$file")){
  // Display filename
  echo $file . "<br>";
  } else if(is_dir("$path/$file")){
  // Recursively call
  // the function if
  // directories found
  outputFiles("$path/$file");
  }
  }
  }
  else{
    echo "ERROR: No files found in the directory.";
  }
  }
  else {
    echo "ERROR: The directory does not exist.";
  }
  }

  // Call the function
  outputFiles("mydir");
?>



Getting a List of All Files of a Certain Kind

When dealing with directory and file structures, you can need to find certain types of files within a directory, such as listing only .text or .png files, for example. The PHP glob() feature, which matches files based on a template, makes this simple.

The PHP code in the following example searches the documents directory for files with the .text extension and displays a list of them. The subdirectories will not be searched.


<?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>";
  }
?>


You may also use the glob() function to find all the files in a directory or its subdirectories. The function described in the following example will recursively list all files within a directory, similar to how the scandir() function did in the previous example.


<?php
  // Define a function to output files in a directory
  function outputFiles($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
  outputFiles("mydir");
?>