Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Change, Make and Remove Directories

chdir(), mkdir() and rmdir()

One can change to a specific directory using the chdir() function - the same way you change to a directory on your command prompt. The syntax for chdir() is:

$TrueOrFalse = chdir("directory name");

In this case the variable $TrueOrFalse contains a TRUE or FALSE value - TRUE on success and FAIL on... failure, for example:

$status = chdir("/www/home");

On a Windows system, this could be something like:

$status = chdir("c:/httpd/www");

The directory of course may not be available. You can test the value of $status just like you did with files - in which case you may want to create the directory yourself. This is where the mkdir() function comes in. The syntax for the $mkdir() function is:

$successOrFailure = mkdir("directory name");

This could be used as in the following example where we create a directory called tutorial inside /www/home/:

$status = mkdir("/www/home/tutorial/");

When the directory finally ceases to be useful, the rmdir() function could be used to remove it. The syntax is pretty much like for the others:

$successOrFailure = rmdir("directory to remove");

In the following code snippet, we remove the directory created earlier:

$status = rmdir("/www/home/tutorial/");

PHP only allows you to remove an empty directory. You must also have the necessary chmod permissions allowing you to do that.

Next we discuss how to open, read and then close directories.

<< Directories | Open, Read and Close Directories >>

JamHitz Productions