If you are looking for the quickest way to check a file extension in PHP, then you have reached the best article to read. Perhaps you need to get file extension in PHP of a file that has been uploaded or use php to check a file extension of an existing file on your website. In any case, the below function will show you how to do it in the least amount of code.
PHP Get File Extension Quickly
<?php $filename = "/home/darian/any.file.name.jpeg"; // get the php file type $extension = pathinfo($filename, PATHINFO_EXTENSION); // display the extension: This will echo out ".jpeg" echo $extension; ?>
How Does The Above Code Work
We use the php function pathinfo() which will take a path (such as “/home/darian/any.file.name.jpeg” in our example) and will return the information about that full path. For example, if we had to run the following code:
$path_info = pathinfo($filename);
It would output an array with information similar to this below
Array ( [dirname] => /home/darian [basename] => any.file.name.jpeg [extension] => jpeg [filename] => any.file.name )
As you can see, the element extension contains the file extension. Now we can speed this function up even further by adding the flag PATHINFO_EXTENSION which tells the function to only return the file extension as a string rather than an array with all the additional information.