Forum Moderators: coopster

Message Too Old, No Replies

check for file types of uploaded files

allow multiple file types

         

coolo

7:37 am on Mar 3, 2004 (gmt 0)

10+ Year Member



So thanks to thread 34, I see how to check an uploaded file to see if it matches one file type. I'm having trouble figuring out to check against 3 file types. For instance if I want to allow picture files to be .gif, .jpg, or .tif, but don't want any other file types to be uploaded.

I was trying to store the 3 file types in an array:

$filesallowed = array(".gif", ".jpg", ".tif");

and then running a foreach statement to check an uploaded file against each possibility.

$last4char = substr($_fileS['userfile']['name'],-4,4);

foreach ($filesallowed as $values){

if ($last4char == $value){
//execute script
}//end if

else {
print "that is not a valid file type.";
}//end else
}//end foreach

Now obviously, for each file that is to be uploaded (if it is a valid file type), 2 iterations of "that is not a valid file type." will be returned and some script will be executed. Can anyone point me to a better way of doing this. Thanks in advance

ahmed

12:09 pm on Mar 3, 2004 (gmt 0)

10+ Year Member



try something like this using in_array():

$filesallowed = array(".gif", ".jpg", ".tif");

$last4char = substr($_fileS['userfile']['name'],-4,4);
if (in_array($last4char, $filesallowed)){
// exceute script
}
else{
print "that is not a valid file type.";
}

that checks if the uploadef file extension is one of the extensionsin the array, if so it runs the script, otherwise prints the error.

I wouldn't rely on using the file extension to check a file type though. a user could rename textfile.txt to textfile.jpg and the above code would allow it. A slightly better way is to check the mime type using :
$_FILES['userfile']['type']

but not all browsers provide that info and again, it can be faked.

A more complicated but much better way of making sure the file is an image is to use the exif_imagetype() function which reads the file itself to determine the type.

see chapter 3 of the php manual (handling file uploads) for more info.

coolo

5:19 pm on Mar 3, 2004 (gmt 0)

10+ Year Member



cool, thank you, thank you.

I think the in_array() function willl work for this. The only people who "should" be uploading anything are site admins, so they shouldn't be doing anything malicious and should know what they are doing. I just want a small check.

Unfortunately, I'm using php v4.1.1 to develop and the exif_imagetype() function (according to the manual) is PHP 4 >= 4.3.0. I will definitely keep this in mind when doing other php scripts.

Thanks again.