0
0
PhpHow-ToBeginner · 3 min read

How to Get File Extension in PHP: Simple Methods Explained

In PHP, you can get a file extension using the pathinfo() function with the PATHINFO_EXTENSION option. This returns the extension part of a filename as a string, for example, "jpg" from "image.jpg".
📐

Syntax

The pathinfo() function extracts information about a file path. To get the extension, use it like this:

  • pathinfo(string $filename, int $option)
  • $filename: The name or path of the file.
  • $option: Use PATHINFO_EXTENSION to get only the extension.
php
$extension = pathinfo('example.txt', PATHINFO_EXTENSION);
💻

Example

This example shows how to get the extension from a filename and print it.

php
<?php
$filename = 'photo.jpeg';
$extension = pathinfo($filename, PATHINFO_EXTENSION);
echo "The file extension is: " . $extension;
?>
Output
The file extension is: jpeg
⚠️

Common Pitfalls

Some common mistakes when getting file extensions in PHP include:

  • Not handling files without extensions, which returns an empty string.
  • Using string functions like explode() incorrectly, which can fail if the filename has multiple dots.
  • Not considering case sensitivity; extensions can be uppercase or mixed case.

Always use pathinfo() for reliable results.

php
<?php
// Wrong way: splitting by dot can fail
$filename = 'archive.tar.gz';
$parts = explode('.', $filename);
echo $parts[count($parts) - 1]; // Outputs 'gz', but might be unexpected

// Right way: use pathinfo
echo pathinfo($filename, PATHINFO_EXTENSION); // Outputs 'gz' correctly
?>
Output
gzgz
📊

Quick Reference

Function/MethodDescriptionExample UsageOutput
pathinfo()Gets parts of a file pathpathinfo('file.txt', PATHINFO_EXTENSION)'txt'
explode()Splits string by delimiter (less reliable)explode('.', 'file.name.txt')['file', 'name', 'txt']
substr() + strrpos()Extract extension manuallysubstr('file.txt', strrpos('file.txt', '.') + 1)'txt'

Key Takeaways

Use PHP's built-in pathinfo() function with PATHINFO_EXTENSION to get file extensions safely.
Avoid splitting filenames by dots manually as it can cause errors with multiple dots.
Handle cases where files may not have an extension; pathinfo() returns an empty string then.
File extensions can be uppercase or mixed case; consider normalizing if needed.