Section 13.7. Dissecting Filename Information


13.7. 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"     } 

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 = 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.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net