[Solved]Upload ==> File Ext Check

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
scts102
Forum Newbie
Posts: 23
Joined: Thu Aug 25, 2005 2:15 pm

[Solved]Upload ==> File Ext Check

Post by scts102 »

Hey,

I have a simple form that uploads an image to my webserver. The form is on, lets call it index.php
index.php POSTs to process.php, which does sql entries and the like. Here is my question: without using the browser mime types, how can I determine the type of file uploaded? And if it is not from a list of accepted exts, then remove the file?

Thanks.
Last edited by scts102 on Sat Oct 29, 2005 12:18 pm, edited 1 time in total.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Upload ==> File Ext Check

Post by alex.barylski »

scts102 wrote:Hey,

I have a simple form that uploads an image to my webserver. The form is on, lets call it index.php
index.php POSTs to process.php, which does sql entries and the like. Here is my question: without using the browser mime types, how can I determine the type of file uploaded? And if it is not from a list of accepted exts, then remove the file?

Thanks.
Could you not just use pathinfo and check the extension against an array of allowed file types???

The other more elaborate way would be to open files upon uploading and check the files header for known signatures or magic cookies...

For instance BMP files or GIF files have (I can't remember where exactly) within the first couple of bytes strings such as like "BM" (BITMAPS) or "GIF89a" (GIF).

Of course...the problems with this approach are obvious :)

EDIT Sorry...to complete your question...

Code: Select all

$tmp_arr = pathinfo($path); // $path is the file just uploaded
$ext_allowed = strtolower($tmp_arr['extension']); // Get the file extension

// Array of safe file extensions to upload
$safe_ext = array('gif', 'bmp', 'jpeg', 'jpg'); // MUST be lower case!!!

if(array_key_exists($ext_allowed, $safe_ext))
  // Move file to permanent location - other than temp directory
else{
  // delete the file - it's not allowed  
  unlink($path);
}

HTH :)

Cheers
scts102
Forum Newbie
Posts: 23
Joined: Thu Aug 25, 2005 2:15 pm

Post by scts102 »

That worked,

Thanks!
Post Reply