# Secure/Bulletproof Image Upload Using PHP

Here is my code that check and upload an image to my website. Is this code really secure against uploading of malicious codes ? Anything i have to add to this code to make it more secure?, I have also blocked execution of PHP in images folder using php_flag engine off in .htaccess of images folder, I can also move images folder out of public_html (root) folder.

<?php
if(isset($_POST['submit'])){ // permenant variabes for upload$target_dir = "./images/";
$allowed = array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif');$maximumsize=5000000000;
//variables form file
$filetempname=$_FILES["image"]["tmp_name"];
$fileinfo = new finfo(FILEINFO_MIME_TYPE);$filemime = $fileinfo->file($_FILES['image']['tmp_name']);
//check if error is set
if(!isset($_FILES['image']['error']) ){ echo 'Invalid upload.'; die(); } // check formultiple uploads and block elseif(is_array($_FILES['image']['error'])){
echo 'Only one file allowed.';
die();
}
elseif($_FILES['image']['error']===0){ // check image size if($_FILES["image"]["size"] > $maximumsize){ echo 'File size exceed maximum size.'; die(); }$ext = array_search($filemime,$allowed, true);
if(false !== $ext){ //upload file by giving new name$newfilename = md5(uniqid('', true));
$newfilename=$newfilename.'.'.array_search($filemime,$allowed);
$target_file =$target_dir .$newfilename; if (move_uploaded_file($_FILES["image"]["tmp_name"], \$target_file)) {
}
else{
die();
}
}
// if file format is wrong
else{
echo "invalid file format";
die();
}
}
// if there is any upload error
else{
die();
}
}
else{
echo "not submited form properly";
}
?>

Any suggestions to make this more secure or any flaws in this script that could be used by hackers to upload shell or php scripts?

• "Is this code really secure?" Secure against what? – Mast Jun 17 '20 at 8:06
• I want to know is there anyway someone can still use this upload feature to upload some php like scripts – markfiz Jun 17 '20 at 8:08
• Like this? – Mast Jun 17 '20 at 8:09
• I want to prevent uploading of shell scripts or something like that to my server. – markfiz Jun 17 '20 at 8:11
• Yes, it's more or less secure. – Your Common Sense Jun 17 '20 at 8:14