Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file extension in PHP? [duplicate]

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?

like image 507
Keith Power Avatar asked Apr 28 '12 22:04

Keith Power


People also ask

How can I get file extension in PHP?

There are a few different ways to extract the extension from a filename with PHP, which is given below: Using pathinfo() function: This function returns information about a file. If the second optional parameter is omitted, an associative array containing dirname, basename, extension, and the filename will be returned.

How do I get the file extension of an input type file?

The full filename is first obtained by selecting the file input and getting its value property. This returns the filename as a string. By the help of split() method, we will split the filename into 2 parts. The first part will be the filename and the second part will be the extension of the file.

What is the function of retrieve filename and extension?

Use pathinfo() Function to Get File Extension in PHP This function extracts the path information from the given path. The correct syntax to use this function is as follows. It is the string containing the path with file name and extension. We will extract path info from this string .


3 Answers

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);
like image 124
ThiefMaster Avatar answered Oct 20 '22 21:10

ThiefMaster


This will work as well:

$array = explode('.', $_FILES['image']['name']);
$extension = end($array);
like image 27
Andrey Avatar answered Oct 20 '22 21:10

Andrey


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

like image 35
Julien Avatar answered Oct 20 '22 22:10

Julien