Find File Extension In PHP

This simple code example uses a combination of strrchr to find the last occurrence of a string and substr to return part of the string in order to find the file extension for a given filename. This is ideal if you want to quickly find a file extension.

$ext = substr(strrchr($fileName, '.'), 1);

This code can be used in the following way.

$fileName = '\path\to\file\afile.wibble';
$ext = substr(strrchr($fileName, '.'), 1);
echo $ext;

The output here is 'wibble';

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
18 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.