How to get the file extension in PHP?

PhpFile Extension

Php Problem Overview


I wish to get the file extension of an image I am uploading, but I just get an array back.

$userfile_name = $_FILES['image']['name'];
$userfile_extn = explode(".", strtolower($_FILES['image']['name']));

Is there a way to just get the extension itself?

Php Solutions


Solution 1 - Php

No need to use string functions. You can use something that's actually designed for what you want: pathinfo():

$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);

Solution 2 - Php

This will work as well:

$array = explode('.', $_FILES['image']['name']);
$extension = end($array);

Solution 3 - Php

A better method is using strrpos + substr (faster than explode for that) :

$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);

But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php

Solution 4 - Php

You could try with this for mime type

$image = getimagesize($_FILES['image']['tmp_name']);

$image['mime'] will return the mime type.

This function doesn't require GD library. You can find the documentation here.

This returns the mime type of the image.

Some people use the $_FILES["file"]["type"] but it's not reliable as been given by the browser and not by PHP.

You can use pathinfo() as ThiefMaster suggested to retrieve the image extension.

First make sure that the image is being uploaded successfully while in development before performing any operations with the image.

Solution 5 - Php

How about

$ext = array_pop($userfile_extn);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeith PowerView Question on Stackoverflow
Solution 1 - PhpThiefMasterView Answer on Stackoverflow
Solution 2 - PhpAndreyView Answer on Stackoverflow
Solution 3 - PhpJulienView Answer on Stackoverflow
Solution 4 - PhpBalanView Answer on Stackoverflow
Solution 5 - PhpilancoView Answer on Stackoverflow