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?
I Made a string clean up script a while back, i think it might help. remember to clean up all your $_POST items like this:
//CLEAN-UP FUNCTIONS
function ms($v) {
$v = str_replace("<br />","",$v);
$v = str_replace(" ","-",$v);
// Replace UTF-8 characters.
$v = str_replace(
array("\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\x93", "\xe2\x80\x94", "\xe2\x80\xa6"),
array("'", "'", '"', '"', '-', '--', '...'),$v);
// Replace their Windows-1252 equivalents.
$v = str_replace(
array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
array("'", "'", '"', '"', '-', '--', '...'),$v);
// Finalize
$v = htmlspecialchars($v, ENT_QUOTES);
//$v = nl2br($v);
return $v;
}
Usage:
$id = ms($_POST['p_id']);