Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way/practice to get the extension of a uploaded file in PHP [duplicate]

Tags:

php

I have a form that allow users to upload files, I however need to get the file extension, which I am able to get, but not sure if I'm using the most effective solution

I can get it using the following ways

$fileInfo = pathinfo($_FILES['File']['name']);
echo $fileInfo['extension'];

$ext = end(explode('.',$_FILES['File']['name']));
echo $ext;

Which method is the best to use or are there even better solutions that would get the extension?

like image 913
Elitmiar Avatar asked Jan 04 '11 07:01

Elitmiar


People also ask

How can I get file extension in PHP?

The simplest way to get file extension in PHP is to use PHP's built-in function pathinfo. Save this answer.

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.


2 Answers

pathinfo($_FILES['File']['name'], PATHINFO_EXTENSION)

  • Use a built-in function whenever possible (what @Sarfraz said in the meantime), and
  • Extract only the needed information (options = PATHINFO_EXTENSION)
like image 101
jensgram Avatar answered Oct 13 '22 01:10

jensgram


Better way - fileinfo extension with PHP >=5.3

PS: do not trust file name extension, any user can any how rename the file extension

like image 33
ajreal Avatar answered Oct 12 '22 23:10

ajreal