PHP

Working With Directories in PHP

Working With Directories in PHP involves creating a directory, changing directories, listing the content of a directory, and also deleting a directory.

PHP provides several in-built functions that enable us to perform operations on directories. The following section discusses some of these functions.

Functions for Working With Directories in PHP

To begin with, we create a directory. For this purpose, there is a function with the name mkdir. The following examples show how to create a single directory, as well as nested directories. These examples are executed on a Windows system.

Creating a Directory

The mkdir() function takes the path of the directory to be created as the mandatory parameter. Therefore, the following example creates a directory with the name dir1 in the current directory.

<?php
   $path='dir1/';
   mkdir($path);
?>

Creating Directory Recursively

The following example shows how to create nested directories. Here, we need to specify the value true for the third parameter called ‘recursive’. So, we also need to specify the mode as the second parameter. However, in a Windows system, this parameter is ignored. As a result of the execution of the following code, these three directories – d1, d2, and d3 will be created.

<?php
   $path='d1/d2/d3';
   mkdir($path, 0777, true);
?>

Changing Directory

For the purpose of changing the directory, PHP provides a function chdir(). Also, the function getcwd() returns the name of the current working directory. The following code shows the current working directory before and after the call to the chdir() function.

<?php
   //display current working directory
   echo 'Current Working Directory...<br>';
   echo getcwd();
   chdir("d1");
   echo '<br>Changed to: <br>';
   echo getcwd();
?>
Working With Directories in PHP - Changing Directory
Working With Directories in PHP – Changing Directory

Listing the Contents of a Directory

Basically, the scandir() function takes the path as a parameter and returns an array of all the files and directories within the given path.

<?php
   $dir="../../Files";
   $arr=scandir($dir);
   print_r($arr);
?>

Output

Listing Directory in PHP
Listing Directory in PHP

Reading the Contents of a Directory with One Entry at a Time

Similarly, the readdir() function returns the content of a directory. However, it returns one entry at a time. Also, we need to call the opendir() function to open the directory.

<?php
   $dir="../../Files";
   $d=opendir($dir);
   while($f=readdir($d))
   {
	echo "Filename: ",$f,"<br>";
    }
?>

Output

Example of readdir() in PHP
Example of readdir() in PHP

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

programmingempire

princites.com

You may also like...