Home / Get the filename extension with PHP

Get the filename extension with 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'];