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 the 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();
}
//check for any upload error
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)) {
echo "uploaded.";
}
//upload failed message
else{
echo "upload failed";
die();
}
}
// if file format is wrong
else{
echo "invalid file format";
die();
}
}
// if there is any upload error
else{
echo "error in upload";
die();
}
}
else{
echo "not submited form properly";
}
?>
Do you have any suggestions to make this more secure or can you spot any flaws in this script that could be exploited by hackers to upload shell or PHP scripts?
.php
or any other harmful extension. You have to watch out for the other code though that may be tricked into including a file of the users choice. \$\endgroup\$