in PHP

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

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email