PHP Basics

Get The File Extension In PHP

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 $file['dirname'] . '<br/>';   // Returns folder/directory
echo $file['basename'] . '<br/>';  // Returns file.html
echo $file['extension'] . '<br/>'; // Returns .html
echo $file['filename'] . '<br/>';  // Returns file
Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial