7

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?

Elitmiar
  • 35,072
  • 73
  • 180
  • 229

3 Answers3

15

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)
jensgram
  • 31,109
  • 6
  • 81
  • 98
  • 5
    but don't trust the input! don't allowing any execution of the uploaded files and preferably move the uploaded files outside the `DocumentRoot` so that even if it is executable, the user can't find it. – Patrick Jan 04 '11 at 07:54
3

Better way - fileinfo extension with PHP >=5.3

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

ajreal
  • 46,720
  • 11
  • 89
  • 119
  • Good solution, but for me this won't work because my development environment currently runs PHP 5.1.6 – Elitmiar Jan 04 '11 at 08:04
  • @Roland - ditch 5.1.* , even 5.2.* is no longer supported ... is time to look for 5.3 , but sometime just too troublesome to upgrade – ajreal Jan 04 '11 at 08:08
  • I agree with you, but I unfortunately am not the owner of the machine, otherwise I would have upgraded. – Elitmiar Jan 04 '11 at 08:23
1

The first (using pathinfo) one is better for the obvious reasons. Use a built-in function for a functionality rather than re-creating it :)

Sarfraz
  • 377,238
  • 77
  • 533
  • 578