Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Dissecting Filename Information

The pathinfo() function takes a filename and returns the same filename broken into various components. It takes a filename as its only parameter and returns an array with three elements: dirname, basename, and extension. Dirname contains the name of the directory the file is in (e.g., c:\windows or /var/www/public_html), basename contains the base filename (e.g., index.html or somefile.txt), and extension contains the file extension, if any (e.g., html or txt).

You can see this information yourself by running this script:

    $fileinfo = pathinfo($filename);
    var_dump($fileinfo);

If $filename were set to /home/paul/sandbox/php/foo.txt, this would be the output:

    array(3) {
            ["dirname"]=>
            string(22) "/home/paul/sandbox/php"
            ["basename"]=>
            string(7) "foo.txt"
            ["extension"]=>
            string(3) "txt"
    }

Tip

In earlier versions of PHP, pathinfo() had problems handling directories that had a period (.) in the name, e.g., /home/paul/foo.bar/baz.txt. This is no longer the case in PHP 5, so pathinfo() is safe to use again.

If all you want to do is get the filename part of a path, you can use the basename() function. This takes a path as its first parameter and, optionally, an extension as its second parameter. The return value from the function is the name of the file without the directory information. If the filename has the same extension as the one you specified in parameter two, the extension is taken off also.

For example:

 $filename = basename("/home/paul/somefile.txt"); $filename ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page