How to get File Extension In PHP - Codewolfy

Working with file uploads is a common task in web development, and knowing how to get file extension in PHP becomes essential for making secure applications. When users upload files in your website, you need to identify the file type to ensure it matches your requirements. Thankfully, PHP supports several built-in methods to extract file extensions from filenames, making validation and processing quite straightforward.

The file extension helps you determine whether the uploaded file is an image, document, or something else. This knowledge gives you the capacity to only accept certain file types and deny potentially hazardous files. In this post, we will go through some ways to get file extensions and how to use them in real-world applications.

Basic Setup: Upload Image and Display File Extension

So, let’s take a practical example where a user can upload an image and we will show its extension. This setup demonstrates the basic concept before going on to different ways. First of all let’s create an HTML file which allows user to upload file:

<!DOCTYPE html>
<html>
<head>
    <title>File Extension Checker</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
        }
        .upload-container {
            border: 2px dashed #ccc;
            padding: 30px;
            text-align: center;
            border-radius: 8px;
        }
        input[type="file"] {
            margin: 20px 0;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            background-color: #f0f0f0;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <h2>Upload Your File</h2>
    <div class="upload-container">
        <form action="upload.php" method="POST" enctype="multipart/form-data">
            <p>Select any file to check its extension</p>
            <input type="file" name="userfile" required>
            <br>
            <button type="submit">Check Extension</button>
        </form>
    </div>
</body>
</html>

Now let’s handle this upload on PHP side where we perform logic and display file extension using different methods.

Using pathinfo() Function to Get File Extension in PHP

The pathinfo() function stands as the most reliable and recommended approach. It parses a file path and returns information about it as an associative array or string.

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    if(isset($_FILES['userfile']) && $_FILES['userfile']['error'] == 0) {
        
        $filename = $_FILES['userfile']['name'];
        
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
        
        echo "Uploaded File: " . htmlspecialchars($filename) . "<br>";
        echo "File Extension: " . htmlspecialchars($extension);
        
    } else {
        echo "Please upload a valid file.";
    }
}
?>

The PATHINFO_EXTENSION constant tells the function to return only the extension part of file name. It works perfectly with simple filenames and handles most common scenarios. For the file “vacation_photo.jpg”, it returns “jpg”. For “report.pdf”, it gives you “pdf”.

Get File Extension using String Functions In PHP

Another way to get file extension is using  substr() and strrpos() string functions in PHP. The strrpos() function finds the last occurrence of a dot in the filename, and substr() extracts everything after it.

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    if(isset($_FILES['userfile']) && $_FILES['userfile']['error'] == 0) {
        
        $filename = $_FILES['userfile']['name'];
        
        $extension = substr($filename, strrpos($filename, '.') + 1);
        
        echo "Uploaded File: " . htmlspecialchars($filename) . "<br>";
        echo "File Extension: " . htmlspecialchars($extension);
        
    } else {
        echo "Please upload a valid file.";
    }
}
?>

With this approach, first you will split string into two using last dot.

Using SplFileInfo Class to Get File Extension in PHP

PHP’s SplFileInfo class provides an object-oriented way to handle file information. This method feels more modern and integrates well with object-oriented codebases.

<
?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    if(isset($_FILES['userfile']) && $_FILES['userfile']['error'] == 0) {
        
        $filename = $_FILES['userfile']['name'];
        
        $fileInfo = new SplFileInfo($filename);
        $extension = $fileInfo->getExtension();
        
        echo "Uploaded File: " . htmlspecialchars($filename) . "<br>";
        echo "File Extension: " . htmlspecialchars($extension);
        
    } else {
        echo "Please upload a valid file.";
    }
}
?>

The SplFileInfo class creates an object containing file details. Its getExtension() method retrieves the extension cleanly.

Using explode() Function

Another approach involves splitting the filename by dots and taking the last element as file extension. This method works well for straightforward scenarios like image files.

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    if(isset($_FILES['userfile']) && $_FILES['userfile']['error'] == 0) {
        
        $filename = $_FILES['userfile']['name'];
        
        $parts = explode('.', $filename);
        $extension = end($parts);
        
        echo "Uploaded File: " . htmlspecialchars($filename) . "<br>";
        echo "File Extension: " . htmlspecialchars($extension);
        
    } else {
        echo "Please upload a valid file.";
    }
}
?>

In above example, the explode function splits file name into array with dot. We will use last part as file extension. However, it’s not idle for all type of file like sample.tar.gz extension file will return gz instead of tar.gz.

Conclusion

There is not a lot of complex code in file extensions extraction with PHP. The pathinfo() function would be the best option for most cases. It’s an integral part of PHP and is well-tested, supporting a wide variety of filename formats. You’ve learned multiple ways to get file extension PHP offers, from simple string functions to object-oriented approaches. Each has its place, depending on your project requirements. In the case of uploading files, always use checking of the extension with additional security measures like MIME type validation and file size limits.