Thursday, September 23, 2010

Working with File System & I/O|Working with Directories

Working with 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 yourPHP 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):
$result = mkdir ("test", "0777")or die ("Failed to create Directory");
if($result)
echo "directory created successfully";
?>
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 CWD (current working directory)
Do you expect a web application to be able to perform all of its file related tasks in a single directory? The answer is NO, it is possible but it will create a mess. 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:


".$cwd."";

?>


save the above script as getCWdir.php and open the page in browser. If your script is fine then you should get the output given below:

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


".$cwd."";
chdir ("/e_drive");
$cwd=getCwd();
echo "After Changing the Directory, Current Working Directory is ".$cwd."";

?>

Save the file as chdir.php and open the open the PHP script in browser to view the output:

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:

".$cwd."";
chdir ("/var");
$cwd=getCwd();
echo "
After Changing the Directory,
Current Working Directory is ".$cwd."
";
$array = scandir(".", 1);
print_r($array);
?>

Save the file and open the page in browser to view the output.
Output:
Try it your self.

No comments:

Post a Comment