Working with Directories in PHP

Sep 23, 2009 Author: City Hall

PHP offers a very powerful set of directory-manipulation functions. The simplest one is chdir(), which like the UNIX command, changes the current working directory of the interpreter: $success = chdir (’/usr/bin’); This function can fail for a number of reasons—for example, because the name you specify points to a directory that doesn’t exist, or because the account under which PHP runs does not have the requisite privileges for accessing it. In these cases, the function returns false. Incidentally, you can find out what the current working directory is by calling

getcwd():echo "The current working directory is " . getcwd();

It is interesting to note that, on some UNIX systems, this function can fail and return false if the any of the parents of the current directory do not have the proper permissions set. Directory creation is just as simple, thanks to the mkdir() function:

if (!mkdir (’newdir/mydir’, 0666, true)) {throw new Exception ("Unable to create directory");}

This function accepts three parameters: the first is the path to the directory you want to create. Note that, normally. only the last directory in the path will be created, and mkdir() will fail if any other component of the path does not correspond to an existing directory. The third parameter to the function, however, allows you to override this behaviour and actually create anymissing directories along the line. The second parameter allows you to specify the access mode for the file—an integer parameter that most people prefer to specify in the UNIX-style octal notation. Note that this parameter is ignored under Windows, where access control mechanisms are different.


views 3710
  1. Add New Comment