Page 1 of 1

verifying file types

Posted: Mon Oct 30, 2006 8:31 am
by sh33p1985
my upload form uses the move_uploaded_file() to upload an image to a specified target folder on my web server. i have verified this works on my local test server so im *assuming* it should work once the upload form goes live.

now this is my first attempt at doing this and im trying to place an emphasis on security and my concerns are:

1) only jpegs allowed

there are limitations on using $_FILES['file']['type'] and mime_content_type() and are easily forged. ive read that files of different types will have a unique starting structue (JPEG is FF D8 FF) so this has given me the idea of checking the file structure to verify its contents although im not entirly sure how to go about doing this.

2) max file size of 2mb

pretty straight forward to check

3) limit on characters in file name

again this should be pretty straight forward to check

any pointers for writing a sound and secure upload form would be greatly appreciated.

thanks

Re: verifying file types

Posted: Mon Oct 30, 2006 8:41 am
by volka
sh33p1985 wrote:1) only jpegs allowed

there are limitations on using $_FILES['file']['type'] and mime_content_type() and are easily forged.
$_FILES[...]['type'] yes, mime_content_type() not so easy, because
sh33p1985 wrote: ive read that files of different types will have a unique starting structue (JPEG is FF D8 FF) so this has given me the idea of checking the file structure to verify its contents although im not entirly sure how to go about doing this.
that's more or less what mime_content_type() does. It compares the file contents (not all of it, only the first significant bytes) with patterns of know file types.
see also http://de2.php.net/getimagesize
sh33p1985 wrote:3) limit on characters in file name

again this should be pretty straight forward to check
define the limits.

Posted: Mon Oct 30, 2006 8:49 am
by JayBird
More helpful info here - viewtopic.php?p=119445#119445

Posted: Mon Oct 30, 2006 9:02 am
by kettle_drum
As volka said the best way to check the mime type is to use the getimagesize() function. As for limiting the characters in the file name - I would personally just rename the files in a standard way so that you dont even need to check for whitespace or other potential illegal file names - if you really need to know what the user named the file, then store this with a reference to the file in a database.

I find there is nothing worse from a usability point of view when a site just throws back errors instead of at least trying to use the data that was submitted.

Posted: Mon Oct 30, 2006 9:36 am
by sh33p1985
ye i see where your coming from, i guess renaming the image to the product ID would make sense as its length is fixed and its meaningful and elimates an error which would have to be caught.