How to get file extension in PHP

get file extension in php
get file extension in php

Getting an extension of a file from PHP string to validate a file for upload is an important task. For example, if you have a file upload which allows you to upload only images then you need to validate the file for an image extension like .jpeg, .jpg, .png, etc. There are so many ways with which we can get the file extension, let’s check how:

1. Using explode() and end():

explode() – breaks a string into an array.
end() – moves the internal pointer to, and outputs, the last element in the array.

<?php
// function to get file extension
function get_extension($file) {
    $array = explode('.', $file);
    $extension = end($array);
    return $extension ? $extension : false;
}

$file_path = "/var/www/html/profile_picture.jpeg";

echo get_extension($file_path);

?>

Output:

jpeg
2. Using pathinfo():

pathinfo() is the function in php which returns information about a file path.

<?php
$file_path = "/var/www/html/profile_picture.jpeg";

$path_parts = pathinfo($file_path);

// print $path_parts array
echo "<pre>";
    print_r($path_parts);
echo "</pre>";

?>

Output:

Array
(
    [dirname] => /var/www/html
    [basename] => profile_picture.jpeg
    [extension] => jpeg
    [filename] => profile_picture
)

so, if you want to output extension use $path_parts['extension'] directly and it will give you jpeg as an output.

3. Using strrchr() with substr():

substr() – Returns a part of a string.
strrchr() – Finds the last occurrence of a string inside another string.

<?php
// function to get file extension
function get_file_extension($file_path) {
    return substr(strrchr($file_path,'.'),1);
}

$file_path = "/var/www/html/profile_picture.jpeg";

echo get_file_extension($file_path);

?>

Output:

jpeg

 

You may also like...

Leave a Reply