How to get a file extension in PHP
Today we’ll explain to you how to get a file extension in PHP. Getting a file extension is very useful for validating a file or file upload. Here, we’ll show you the different ways to get a file extension from PHP string.
Different ways to get a file extension in PHP
- Using Explode() function
- Using substr() and strrchr() function
- Using strrpos() function
- Using pathinfo() function
Let’s start with an example. Assume that we have an image named `cluemediator.jpg`.
1. Using Explode() function
We will explode the file variable with `.` and get the last element of an array using end() function.
<!--?php
$fileName= "cluemediator.jpg";
$file_name_array = explode(".", $fileName);
$extension = end($file_name_array);
echo $extension;
?-->
// Output: jpg
2. Using substr() and strrchr() function
Here, we will find the last occurrence of `.` with the use of strrchr() function that returns the `.jpg` string. Then we need to remove the first character of the string using the substr() function, it will return the file extension `jpg`.
<!--?php
$fileName= "cluemediator.jpg";
$extension = substr(strrchr($fileName, '.'), 1);
echo $extension;
?-->
// Output: jpg
3. Using strrpos() function
In this way, first we will find the position of the last occurrence of `.` from the filename. Then increase that position by 1 so that it explodes a string from `.`.
<!--?php
$fileName= "cluemediator.jpg";
$extension = substr($fileName, strrpos($fileName, '.') + 1);
echo $extension;
?-->
// Output: jpg
4. Using pathinfo() function
This is a very simple way to get file extension using the pathinfo() function. It will return the information of a file i.e. directory name, basename, extension, and filename.
This function takes two parameters. First one is filepath and second one is optional parameter that is an option which you want from file path.
You can use the options as given below.
- PATHINFO_DIRNAME - Returns the directory name
- PATHINFO_BASENAME - Returns the base name
- PATHINFO_EXTENSION - Returns the file extension
- PATHINFO_FILENAME - Returns the file name
<!--?php
$fileName = "cluemediator.jpg";
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
echo $extension;
?-->
// Output: jpg
If we have not passed the second parameter `options` then it will return the array as shown below example.
<!--?php
$fileName = "../images/cluemediator.jpg";
$extension = pathinfo($fileName);
print_r($extension);
?-->
// Output:
Array
(
[dirname] => ../images
[basename] => cluemediator.jpg
[extension] => jpg
[filename] => cluemediator
)
That’s it for today.
Thank you for reading. Happy Coding..!!