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:
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.
<?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 learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: A working example: making a counter >>
Previous chapter: Retrieving a file's status
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.