How to Get File Extension in PHP using pathinfo

Extracting file extensions is a fundamental task in PHP helper scripts, file upload systems, and media management. This article explains how to use PHP’s built-in pathinfo() function to quickly and securely retrieve a file’s extension. You will learn the function’s syntax, how to use specific flags for direct extraction, and how to handle common edge cases like files with multiple extensions or no extensions at all.

Understanding the pathinfo() Function

The pathinfo() function analyzes a file path and returns information about it. By default, it returns an associative array containing four elements: * dirname: The directory path. * basename: The filename with the extension. * extension: The file extension. * filename: The filename without the extension.

Syntax

pathinfo(string $path, int $flags = PATHINFO_ALL): array|string

Extracting the Extension Directly

While you can grab the extension from the returned associative array, the most efficient way to extract only the file extension is by passing the PATHINFO_EXTENSION flag as the second argument. This instructs PHP to return only the extension as a string.

Code Example:

<?php
$filepath = "/var/www/uploads/document.pdf";

// Extract the extension directly
$extension = pathinfo($filepath, PATHINFO_EXTENSION);

echo $extension; // Outputs: pdf
?>

Extracting the Extension from the Array

If you need other details about the file path alongside the extension, you can call pathinfo() without the second argument and access the extension key from the resulting array.

Code Example:

<?php
$filepath = "images/avatar.png";

$fileParts = pathinfo($filepath);

if (isset($fileParts['extension'])) {
    echo $fileParts['extension']; // Outputs: png
}
?>

Handling Edge Cases

When using pathinfo(), it is important to understand how it behaves under specific file naming conditions:

1. Files with No Extension

If a file does not have an extension (for example, a system file like LICENSE or .htaccess), pathinfo() will return an empty string when using PATHINFO_EXTENSION. If you are using the array method, the extension key will not be present in the returned array.

2. Files with Multiple Extensions

If a file has multiple extensions, such as archive.tar.gz, pathinfo() only extracts the final extension.

$file = "archive.tar.gz";
echo pathinfo($file, PATHINFO_EXTENSION); // Outputs: gz

3. Case Sensitivity

The pathinfo() function returns the extension exactly as it is written in the path. If the file is named photo.JPG, the function returns JPG. To ensure consistency when validating file types, it is best practice to convert the output to lowercase using strtolower().

$file = "photo.JPG";
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
echo $extension; // Outputs: jpg