Possible Duplicate:
Security threats with uploads
I've been searching for a good script/tutorial for secure image upload, but whatever I find, reading the comments there seem to be issues with the script as far as security is concerned. So I tried to compose my on script. I would like to ask for any security suggestions on this.
//create arrays from allowed extensions and types
$allowed_exts = array("jpg", "jpeg", "png", "gif");
$allowed_types = array("image/jpeg", "image/png", "image/gif");
//extract extension from uploaded file
$ext = strtolower(substr($_FILES["image"]["name"], strrpos($_FILES["image"]["name"], ".") + 1));
I first check if the extension is one of the allowed
if(in_array($ext, $allowed_exts) === false){
echo "Only .jpg, .png, .gif allowed";
}
Then check if the type is one of the allowed
elseif(in_array($_FILES["image"]["type"], $allowed_types) === false){
echo "Only .jpg, .png, .gif allowed";
}
Then check the filesize
elseif($_FILES["image"]["size"] > 2100000){
echo "File is too big";
}
Now use getimagesize to check for dimensions
elseif(!getimagesize($_FILES["image"]["tmp_name"])){
echo "File is not an image";
} else {
I create a random file name
$filename = mt_rand(1000,99999)."_".$_POST['p_id'].".jpg";
If this is all fine, I create a thumb using GD. In short (incase its a jpeg):
a. imagecreatefromjpeg -> from uploaded file
b. imagecreatetruecolor -> with desired thumbnail dimensions
c. imagecopyresampled -> modify the image created under a.
d. imagejpeg -> save image to destination
So, as I've read this should eliminate most problems that come with the image, but I m sure I missed something important.
The directory I write the files to has 755 permission, but I think I have to make more restrictions on the directory by putting a .htaccess in the folder? What should be in there?