Can We find out the extension of the original file from $_FILES["file"]["tmp_name"]
? For example jpg or png etc?
Asked
Active
Viewed 1.2e+01k times
4 Answers
114
$name = $_FILES["file"]["name"];
$ext = end((explode(".", $name))); # extra () to prevent notice
echo $ext;

Dejan Marjanović
- 19,244
- 7
- 52
- 66
-
1Make sure to remember that a filename extension is just a hint on the real content. It can be of total different content. – user1610743 Apr 06 '14 at 21:27
-
3@user1610743 it's a general rule not to trust any user content. Obviously one could check file headers and make sure it matches the extension. Example would be images (JPEG, PNG, etc.). – Dejan Marjanović Apr 06 '14 at 21:52
-
@webarto Just felt like adding this comment since this is the first result that pops up on google search.. Theres been many vulnerable web things due to unsafe file extension checking. – user1610743 Apr 06 '14 at 21:59
-
@user1610743 I understand, I haven't added that notice because it would be out of the scope of the question, but since it's accepted I might do that to hopefully prevent someone making a mistake. Thanks. – Dejan Marjanović Apr 06 '14 at 22:13
-
1Lets make the world a little bit safer :-) – user1610743 Apr 06 '14 at 22:48
-
Not sure if it didn't return a notice when first posted, but as of PHP8, this does return a notice. The reasoning is explained here: https://stackoverflow.com/questions/16498166/using-end-with-explode-does-not-work – tb. Jan 18 '23 at 04:34
110
You could use pathinfo()
:
$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];

John Ballinger
- 7,380
- 5
- 41
- 51

JKS
- 3,710
- 2
- 29
- 40
-
21
-
1
-
@JohnBallinger : Dear Sir, what about the first answer which is the accepted one? is that the better option than this one? – sqlchild Sep 18 '19 at 08:05
-
Note that this does not look at the file content at all, it only looks at the string. Renaming your `image.png` to `image.mp3` without altering the data does **not** give you `png` as a result – Typewar Jun 11 '22 at 13:01
1
Yes you can use $_FILES['file']['name']
to get the original name of the uploaded file. Just keep in mind that the extension may not always represent the real contents of the file.

GWW
- 43,129
- 11
- 115
- 108
-
I understand that we can find with the 'name', but i was wondering if we can find using only tmp_name. – Peter Mar 25 '11 at 00:30
-
1@Peter, `tmp_name` is a random filename generated by PHP. You can only do this by looking at the actual original name. – Charles Mar 25 '11 at 00:58
1
Yes, assuming it's accurately named. It will retain its original name and extension.

thf
- 594
- 1
- 10
- 22