4 Most Important Directory Functions in PHP

Mar 07, 2014, by admin

When writing PHP scripts that need to deal with the file-system to change the current directory, creating new directories, change the root directory, gets the current working directory, list files and directories inside the specified path and many more. For this, PHP provides a number of built-in directory functions that can be used to perform such tasks.

Creating Directory

A new directory can be created in PHP using the mkdir() function. This function takes a path to the directory to be created. A second, optional argument allows the specification of permissions on the directory.

mkdir(“/home/php_files”, 0777);

The above example will create directory similar to:

/home/php_files

Gets the current working directory

You can get the current working directory in PHP by using getcwd() function.

echo getcwd();

The above example will output:

/home/php_files

Change directory

The current working directory can be changed using the chdir() function. It takes only one argument the path of the new directory.

chdir(‘include’);

The above example will output:

/home/php_files/include

Change the root directory

The PHP function chroot() changes the root directory of the current process to directory, and changes the current working directory to “/”.

chroot(“/home/php_filesinclude/include”);
echo getcwd();

The above example will output:

/

Read directory content

The function opendir() opens up directory handle and readdir() will read directory contents.

$dir = “/home/php_files/images/”;
// Open up a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
      echo “File:” . $file . “
“;
    }
    closedir($dh);
  }
}

The above example will output:

File: header.png
File: home.png
File: save.png