PHP Cheat Sheet: Working with Directories

1. Retrieving a Path’s Filename:

$path = '/home/www/data/users.txt';
$file_nm = basename($path);  // "users.txt"
$file_nm_1 = basename($path, ".txt");  // "users", no extension.

2. Retrieving a Path’s Directory:

$path = '/home/www/data/users.txt';
$dir_nm = dirname($path)  // "/home/www/data"

3. Learning More about a Path:

$pathinfo = pathinfo('/home/www/htdocs/book/chapter10/index.html');
echo $pathinfo['dirname'];   // "/home/www/htdocs/book/chapter10"
echo $pathinfo['basename'];   // "index.html"
echo $pathinfo['extension'];   // "html"
echo $pathinfo['filename'];   // "index"

4. Identifying the Absolute Path

$imgPath = '../../images/cover.gif';
$absolutePath = realpath($imgPath);   // "/www/htdocs/book/images/cover.gif"

5. opendir() and readdir()

if ($dh = @opendir($directory)) {
    while (($filename = readdir ($dh))) {
        if ($filename != "." && $filename != "..") {
            if (is_file($directory."/".$filename)) {
                echo "File: $filename";
            }
            if (is_dir($directory."/".$filename)) {
                echo "Dir: $filename";
            }
        }
    }
    closedir($dh);
}

 

To top