How to get a File Extension in PHP

How to Get a File Extension in PHP

There are some scenarios when you need to extract a file extension in any programming language.  Today tutorial will demonstrate the easiest way to extract or get a file extension in PHP.

A file extension is a string of characters(usually 4 or 3) preceded by a full stop indicating the file format.

There are many reasons you would want to extract a file extension in PHP such as validating file uploads, to show a relevant preview of different files and so on.

How to Extract File Extension in PHP

The following code shows how you can get a file extension in PHP, We will go ahead and show you how you can validate such extensions.

 




 

if(isset($_FILES['order-doc-upload']['name'])){
    $fileName = $_FILES['order-doc-upload']['name'];
    $fileSize = $_FILES['order-doc-upload']['size'];
    $fileType = $_FILES['order-doc-upload']['type'];
    $tmpName  = $_FILES['order-doc-upload']['tmp_name'];


    $base = basename($fileName);
    $extension = strtolower(substr($base, strlen($base)-4, strlen($base)));
    echo $extension ; // this will return the file extension of any give file

}

 

Just to explain a few things happening from the code above, $fileName variable returns the full file path. To get the name of the file, we used basename($filename), this returns the name of the file without pathname, thanks to PHP inbuilt method basename(). From the base name of the file, we calculate four characters from the last character of the filename.

How to Validate File Extensions in PHP

Validating file extensions in PHP is very vital to eliminate spam as well as unwanted files for a given context. The following code illustrates how you can validate the extracted file extension in PHP.

if(isset($_FILES['order-doc-upload']['name'])){
  $fileName = $_FILES['order-doc-upload']['name'];
    $fileSize = $_FILES['order-doc-upload']['size'];
    $fileType = $_FILES['order-doc-upload']['type'];
    $tmpName  = $_FILES['order-doc-upload']['tmp_name'];


    $base = basename($fileName);
    $extension = strtolower(substr($base, strlen($base)-4, strlen($base)));
    $allowed_extensions = array(".png",".jpg","jpeg", '.zip', 'docx', '.doc', 'docs', '.ppt', '.pdf', '.txt');



    if(in_array($extension,$allowed_extensions)) {
          // upload your files here
    } else {
        echo "Invalid file extension";
    }
}