W3jar
202 words
1 minutes

How to Get a File Extension in PHP

2024-08-16

To get a file extension in PHP, you can use the pathinfo() function, which provides information about a file path. Here’s a basic example of how you can use it to retrieve the file extension:

<?php
// Specify the file path
$filePath = 'example/document.txt';

// Get the file extension
$fileInfo = pathinfo($filePath);
$fileExtension = isset($fileInfo['extension']) ? $fileInfo['extension'] : '';

// Output the file extension
echo "File extension: " . $fileExtension;
?>

Explanation:#

  • pathinfo($filePath): This function returns an associative array containing information about the file path, such as directory name, basename, extension, and filename.
  • isset($fileInfo['extension']) ? $fileInfo['extension'] : '': This checks if the extension key exists in the array and returns it if it does. If not, it returns an empty string.

Additional Notes:#

  • If the file doesn’t have an extension, $fileExtension will be an empty string.
  • pathinfo() is versatile and can also provide other details like the directory name, basename, and filename without extension. You can access these using keys like 'dirname', 'basename', and 'filename'.

Example with a different file path:#

<?php
$filePath = '/var/www/html/index.php';
$fileInfo = pathinfo($filePath);
$fileExtension = isset($fileInfo['extension']) ? $fileInfo['extension'] : '';
echo "File extension: " . $fileExtension; // Output: php
?>

This method is straightforward and works well for most use cases involving file path manipulation in PHP.