Directory Functions in PHP

Introduction

This article explains Directories in PHP; how to show or get all the information about directories and contents. For this I use the important and useful functions such as chdir(), chroot(), dir(), closedir(), getcwd(), opendir(), readdir(), rewinddir() and scandir(). I discuss them step-by-step. The directory functions are parts of the PHP core.

Syntax

chroot(directory);

 

Parameter Description
Directory Required specifies new root directory.

Example

This function basically changes the root directory of the current process and this function returns true on success otherwise returns false. This function does not work on the Windows platform since Wndows does not have equivalent functionality.

<?php

chroot("/path/to/your/chroot/");

echo getcwd();

?>

Output

/

Syntax

chdir(directory);

 

Parameter Description
Directory Required. Specifies the directory to change to.

Example

This function changes the current directory.

<?php

//get current dire

echo getcwd();

echo "<br />";

//change to the file dir

chdir("gallery");

echo "<br />";

echo getcwd();

?>

Output

cal.jpg

Syntax

scandir(directory,sort,context);

 

Parameter Description
Directory Required; specifies the file name to scan.
sort Specifies the sort order.
context A set of options that can modify the behavior of the stream.

Example

This function returns the file in an array. This function returns an array on success otherwise returns false.

<?php

echo "<pre>";print_r(scandir("gallery"));

?>

Output

cal1.jpg

Syntax

readdir(dir_stream);

 

Parameter Description
Directory Required. Specifies the directory handle to use.

Example

This function returns the entry from a directory. This function returns a filename on success otherwise returns false.

<?php

//Open gallery directory

$dir = opendir("gallery");

while (($file = readdir($dir)) !== false)

  {

  echo "filename: " . $file . "<br />";

  }

closedir($dir);

?>

Output

cal2.jpg

Syntax

getcwd();

 

Parameter Description
   

Example

This function returns the current directory. This function returns the current directory on success otherwise returns false.

<?php

echo getcwd();

?>

Output

dynamic check.jpg


Similar Articles