8.8 Dissecting filename information: pathinfo() and basename()This is NOT the latest copy of this book; click here for the latest version.
array pathinfo ( string path)
string basename ( string path [, string suffix])
The pathinfo() function is designed to take a filename and return 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").
Here is an example of pathinfo() in action:
<?php
$fileinfo = pathinfo($filename);
var_dump($fileinfo); ?>
If $filename were set to '/home/paul/sandbox/php/foo.txt', that script would output the following:
array(3) {
["dirname"]=>
string(22) "/home/paul/sandbox/php"
["basename"]=>
string(7) "foo.txt"
["extension"]=>
string(3) "txt"
}
Author's Note: in earlier versions of PHP, pathinfo() had problems handling directories that had a full stop . 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:
<?php
$filename = basename("/home/paul/somefile.txt");
$filename = basename("/home/paul/somefile.txt", ".php");
$filename = basename("/home/paul/somefile.txt", ".txt"); ?>
The first line sets $filename to "somefile.txt", the second also sets it to "somefile.txt" because the filename does not have the extension .php, and the last line sets it to "somefile".
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|