Get The File Extension In PHP

Getting a file extensions from a PHP string is an important task on validating a file for a upload. For example if you have a file uploader which you only want to use for image uploads then you need to validate the file extension is of an image extension. Here is a PHP function to get the extension of a string. It will explode the string on any "." and get the last of the array.


<?php
function get_extension($file) {
 $extension = end(explode(".", $file));
 return $extension ? $extension : false;
}
?>

Pathinfo Function

Another option to get the file extension from a string is to use the pathinfo function, this takes a maximum of 2 parameters. The first parameter is the filepath, the second parameter is the option of return that you want from the file path. The number of options that you can use is: - PATHINFO_DIRNAME - Returns the directory name

  • PATHINFO_BASENAME - Returns the base name
  • PATHINFO_EXTENSION - Returns the file extension
  • PATHINFO_FILENAME - Returns the file name

If none of the options are provided then the function will return all 4 in an array.

$file = 'folder/directory/file.html';
$ext = pathinfo($file, PATHINFO_EXTENSION);

// Returns html
echo $ext;


$file = 'folder/directory/file.html';
$ext = pathinfo($file);

echo $ext['dirname'] . '<br/>';   // Returns folder/directory
echo $ext['basename'] . '<br/>';  // Returns file.html
echo $ext['extension'] . '<br/>'; // Returns .html
echo $ext['filename'] . '<br/>';  // Returns file

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring