HomePHP Page 5 - File And Directory Manipulation In PHP (part 2)
The Right Path - PHP
Now that you know the basics of reading and writing files, this second segment of our tutorial on the PHP filesystem API takes you into deeper waters, showing you how to copy, delete and rename files; scan directories; work with uploaded files over HTTP; perform pattern matches on file names; and read and write to processes instead of files.
In addition to functions that allow you to obtain information on file sizes, permissions and modification times, PHP also offers a number of functions designed to manipulate file and path names, and split a file path into its constituent components. The two most commonly-used ones here are the basename() function, which returns the filename component of a path, and the dirname() function, which returns the directory name component of a path
The following example demonstrates the basename() and dirname() components in action, by splitting a file path into its constituents:
<?php
// set path
$path = "/usr/local/apache/bin/httpd";
// print directory name
echo "Directory is " . dirname($path) . "\r\n";
?>
Here's the output:
File is httpd Directory is /usr/local/apache/bin
You can also use the pathinfo() function to obtain this information - this function returns an associative array containing keys for directory name, file name and file extension. Take a look at this next script, which returns this information for the directory holding the currently executing script.
<?php
// parse current file path
$info = pathinfo($_SERVER['PHP_SELF']);