RSS

PHP Cheat Sheet: Working with Directories

Mon, Dec 12, 2011

Programming

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);
}

 

, ,

This post was written by:

- who has written 16 posts on ColorWalk.com.


 

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word