Grab file extension into string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
seodevhead
Forum Regular
Posts: 705
Joined: Sat Oct 08, 2005 8:18 pm
Location: Windermere, FL

Grab file extension into string

Post by seodevhead »

Hey guys... I am using a file upload form, but I am also using a thumbnail creation class with it to make thumbnail images. Everything works great, however I need to save the file extension (ie. .jpg .gif .png, etc) as a string in a variable.

Is there anyway to gather this from the file? I know I can view the MIME type with $_FILES[$filename]['type'], but that gives me 'image/jpg'... and all I want is 'jpg'. Any help would be GREATLY appreciated!!! Thanks.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

never rely on the type supplied to be correct (it's easily spoofed, and php doesn't check it)

Instead you should check the file itself (not the name supplied). For images, getimagesize() works quite well.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Hmm... no need for mime_content_type, then...
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

Isn't the mime type already in $_FILES['foo']['type'] ? Anyways to get the jpg out of that do:

Code: Select all

$mime = explode('/',$_FILES['foo']['type'];
$category = $mime[0]; // image
$type = $mime[1]; // jpg
Feyd is right though, don't rely on this information
User avatar
seodevhead
Forum Regular
Posts: 705
Joined: Sat Oct 08, 2005 8:18 pm
Location: Windermere, FL

Post by seodevhead »

Hey guys... I used feyd's suggestion and getimagesize() works great since it returns the number corresponding to the file extension as the #2 element in the array.

You say I shouldn't rely on the mime type info because it is easily spoofed. Which method would you suggest I use to ensure the uploaded file is of the proper type? Thanks!!! :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

the only way to ensure type is by analysing the file.
Useful Posts wrote:Some helpful information determining a file's actual type: Upload Script
User avatar
seodevhead
Forum Regular
Posts: 705
Joined: Sat Oct 08, 2005 8:18 pm
Location: Windermere, FL

Post by seodevhead »

thanks feyd!
Post Reply