Get the filename extension with PHP
Posted February 22nd, 2010 in PHP
I've covered how to get the filename and directory name from a full path with PHP before and did include a section which happened to include how to get the filename extension as well, but I continue to find myself unable to remember the name of the function so I've put that part of the previous post into this new one with a title specific to finding the extension.
Get the directory name, filename and extension with pathinfo()
PHP's pathinfo() function returns an associative array containing the basename, dirname, extension and (from PHP 5.2.0) the filename without the extension.
print_r(pathinfo($path));
will echo
Array
(
[dirname] => /var/www/mywebsite/htdocs/images
[basename] => myphoto.jpg
[extension] => jpg
[filename] => myphoto
)
To get just the extension you could do something like this, assuming you would rather save the extension to a separate variable rather than use the returned associative array:
$pathinfo = pathinfo($path); $extension = $pathinfo['extension'];
Related posts:
- Get the directory name and filename from a full path name with PHP (Thursday, December 10th 2009)
- Using PHP's scandir() function to find files in a directory (Friday, July 17th 2009)
- Using PHP's glob() function to find files in a directory (Thursday, July 2nd 2009)
- Reading through a directory with PHP (Thursday, June 18th 2009)

Comments
blog comments powered by Disqus