Getting file extension in php

In this php tutorial you will learn how to get the file extension from a string in php. Sometimes during web development you may need to get the file extension, so let's have a look over how to do this.

There are different ways to do this. Let's have a look over each of them


1) Using explode()

The simplest and easiest way of getting file extension is to use the php built-in function explode.

The explode() function breaks a string into an array.

It takes three parameters in which two of them are required and one is optional.

a) The first required parameter is separator that specifies where to break the string.
b) The second required parameter is string that specifies the string to split.
c) The optional parameter is limit that specifies the maximum number of array elements to return.

So let's have a look over how to get the file extension using explode() method.

<?php
$filename="picture.jpg";
$fileArray=array();
$fileArray =explode('.',$filename);
$file_extension=$fileArray[1];
echo $file_extension;
?>


or you can made a custom php function and call explode() method in it and in the end return the value

<?php
function get_file_extension($file_name)
{
return end(explode('.',$file_name));
}


$filename="picture.jpg";
$file_extension=get_file_extension($filename);
echo $file_extension;
?>

2) Using PATHINFO_EXTENSION

Another way to get the file extension is to use the pathinfo which is an array that contains dirname, basename, extension and file name. Right now we are only interested in the file extension so I am going to call it directly.

<?php
$filename="picture.jpg";
$file_extension = pathinfo($filename,PATHINFO_EXTENSION);
echo $file_extension;
?>


Or you can do like this

<?php
function get_file_extension($file_name)
{
return pathinfo($file_name, PATHINFO_EXTENSION);
}

$filename="picture.jpg";
$file_extension =get_file_extension($filename);
echo $file_extension;
?>

3) Using substring and string char

You can use substring and string char to determine the file name length and position to get the file extension. Let’s have a look over how to do this

<?php
function get_file_extension($file_name)
{
return substr(strrchr($file_name,'.'),1);
}

$filename="picture.jpg";
$file_extension =get_file_extension($filename);
echo $file_extension;
?>

So these are the different ways to get the file extension in php.

0 comments: