Working with Directories in PHP

Revision as of 18:59, 11 May 2009 by Neil (Talk | contribs)

Revision as of 18:59, 11 May 2009 by Neil (Talk | contribs)

PreviousTable of ContentsNext
PHP, Filesystems and File I/OAn Overview of HTML Forms


<google>BUY_PHP</google>


Now that we have spent some time looking at how to work with files in PHP (see PHP, Filesystems and File I/O) it is now time to look at how to work with file system directories. PHP provides a number of functions that can be used to perform tasks such as identifying and changing the current directory, creating new directories, deleting existing directories and list the contents of a directory.


Creating Directories in PHP

A new directory can be created in PHP using the mkdir() function. This function takes a path to the directory to be created. To create a directory in the same directory as your PHP script simply provide the directory name. To create directory in a different directory specify the full path when calling mkdir().

A second, optional argument allows the specification of permissions on the directory (controlling such issues as whether the directory is writable):

<?php
$result = mkdir ("/path/to/directory", "0777");
?>

<google>ADSDAQBOX_FLOW</google>

Deleting a Directory

Directories are deleted in PHP using the rmdir() function. rmdir() takes a single argument, the name of the directory to be deleted. The deletion will only be successful if the directory is empty. If the directory contains files or other sub-directories the deletion cannot be performed until those files and sub-directories are also deleted.


Finding and Changing the Current Working Directory

It is unlikely that a web application will be able to perform all of its file related tasks in a single directory. For this reason, it is vital to be able to both find out the current working directory, and change to another directory from within a PHP stript.

The current working directory can be identified using the getCwd() function:

<?php
$current_dir = getCwd();

echo "Current directory is $current_dir";
?>

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

<?php

$current_dir = getCwd();

echo "Current directory is $current_dir <br>";

chdir ("/tmp");

$current_dir = getCwd();

echo "Current directory is now $current_dir <br>";
?>

Listing Files in a Directory

The files in a directory can be read using the PHP scandir() function. scandir() takes two arguments. The first argument is the path the directory to be scanned. The second optional argument specifies how the directory listing is to be sorted. If the argument is 1 the listing is sorted reverse-alphabetically. If the argument is omitted or set to 0 the list is sorted alphabetically:

<?php
chdir ("/tmp");

$current_dir = getCwd();

echo "Current directory is now $current_dir";

$array = scandir(".", 1);

print_r($array);
?>