The other day I was building some file handling functionality into a project I was working on when i came to thinking about the best way to retrieve the extension of a filename with PHP.
The first approach that came to mind was using explode statement to split the string at the full stop giving the extension of the file in the last array element. The second was using substr and strrchr in combination similar to below:
[codesyntax lang="php"]
$fileName = 'myfile.mp4'; $fileExtension = substr(strrchr($fileName, '.'), 1);
[/codesyntax]
This also does the job well, but they are not perfect. Especially if the user provides a file with multiple periods within it. This got me thinking there must be an easier approach and it just so happens there is! The PHP pathinfo atatement can be used to return all sorts of useful information about a file and its path if provided. For example the extension can be retrieved via pathinfo by calling it then accessing the “extension” element in the returned array e.g
[codesyntax lang=”php”]
$fileDetails = pathinfo('myfile.mp4'); $fileExtension = $fileDetails['extension'];
[/codesyntax]
Using pathinfo you can request to recieve only the file extension back by also providing a flag. Below the PATHINFO_EXTENSION flag is set to return just the extension e.g
[codesyntax lang=”php”]
$fileExtension = pathinfo('myfile.mp4', PATHINFO_EXTENSION);
[/codesyntax]
As always one thing to take into account is the pathinfo statement simply returns the file extension as it is in the filename. You should still check the case of the extension i.e
mp4 is not equal to MP4
Full details on pathinfo can be found on the PHP site manual page.