PHP Strings: How to Get the Extension of a File

EXE or GIF or DLL or …

Most of the code chunks I’ve seen about getting a file extension from a string are based on some sort of string manipulation.

Get the Filename Extension with PHP
If you want to get the filename extension with PHP is better to use pathinfo() than string manipulations

$filename = '/my/path/image.jpeg';
echo substr($filename, strrpos($filename, '.') + 1);

Howerver there is a more elegant solution.

$filename = '/my/path/image.jpeg';
echo strtolower(pathinfo($filename, PATHINFO_EXTENSION));

Thus you rely on PHP built in functions and it’s harder to overlook the exact string manipulation approach.

3 thoughts on “PHP Strings: How to Get the Extension of a File

  1. Wouldn’t work for .tar.gz though would it, a better method is pathinfo(‘/path/to/file.tar.gz’, PATHINFO_EXTENSION); or if your using SPL SplFileInfo::getExtension(); works

  2. Hello Friend, how to distinguish the file among .php file, .pdf, .mp3, .jpg etc using php.
    I want fetch the name separatly. please help me out.

Leave a Reply

Your email address will not be published. Required fields are marked *