View Tutorial Metadata Edit Content Revision History Add to Watchlist Add New Tutorial How to get the file extension in PHP 5

Obtaining the the file extension out of a file name

Get a file extension in PHP

There are moments when you need to find the extension of a certain file (for example after doing a file upload - File uploads in PHP -, you want to see if the uploaded file matches your allowed extensions).

It is pretty simple to do this using the next function which accepts as an input parameter a full path or only the filename and returns the file extension.

The algorithm is this : it checks for the character '.' (dot) and if it doesn't find it then it means our file doesn't have any extension. In case it finds the '.' (dot) character then it returns in lowercase all the text after the last dot.

function getFileExtension($filePath){
	if (strpos($filePath,'.') === false){
		return '';
	}
	return strtolower(substr(strrchr($filePath, '.'), 1));
}

The function above works even for getFileExtension("name.example.txt"), because the strrchr function returns the rightmost occurrence of the searched dot character.

Using pathinfo()

You can also use the pathinfo() function, described in the PHP manual.

$originalFileName = 'example.file.txt';

$fileExtension = '';

$info = pathinfo($originalFileName);
if (isset($info['extension']))
    $fileExtension = $info['extension'];

print $fileExtension;

Only plain text supported.

Optional

Required - will be kept private

Optional

 
 

Rating: (3+, 1-) In: PHP 5