I have written [PHP code][ to upload image/s to server.
(To see the result, open the JavaScript console of your browser, look at the Network tab or the Console tab.)
The code is also available and runnable on paste.ofcode.org.
I would like to know if this code is secure for uploading valid images.
<?php
$IMAGE_SIZE = 2097152; // 2mb ht tp:/ /ww w.convertunits.com/from/MB/to/byte
$MAX_IMAGES = 30;
if(!empty($_FILES['fileToUpload']['name'][0])) {
foreach($_FILES["fileToUpload"]['tmp_name'] as $key=>$imgLocation){}
if($key<$MAX_IMAGES){
foreach($_FILES["fileToUpload"]['tmp_name'] as $key=>$imgLocation){
if($imgLocation){//filename exist
$imageName = $_FILES["fileToUpload"]['name'][$key];
if(checkMime($imgLocation)&&
checkExtension($imageName)&&
checkByExif($imgLocation)&&
checkSize(filesize($imgLocation))&&
checkImageName($imageName)){
echo $usr_dir = "img/".changeImageName($imageName).".".getExtension($imageName);
if(move_uploaded_file($imgLocation, $usr_dir)){
echo "<br/>success full uploaded<br/>";
}else{
echo "<br/> File Not uploaded<br/>";
}
}else{ echo "<br/>Invalid File<br/>";}
}else{echo " No Image uploaded";}
}
}else echo "<br/> - Only 30 Images are allowed -<br/>";
}else{
echo "No Image Is selected";
}
function handleError($msg){
//return json_encode();
}
function checkImageName($imagename){
$imagename = pathinfo($imagename, PATHINFO_FILENAME);
if(strpbrk($imagename, "\\/?%*' :|\"<>") === FALSE&&$imagename){
if (strlen($imagename) >= 1 && strlen($imagename)<= 30){
return true;
}else{
return false;
//HandleError('Invalid file name');
}
}else{
return false;
}
}
function issetImage($image_tmpName){
return (file_exists($image_tmpName) || is_uploaded_file($image_tmpName));//return ture and false
}
function checkMime($image_tmpName){
if(issetImage($image_tmpName)){
$whitelist = array("image/gif","image/png","image/jpeg","image/jpg","image/bmp");
$imageinfos = getimagesize($image_tmpName);
$imageTypes = $imageinfos['mime'];
if(in_array($imageTypes, $whitelist)){
return true;
}else{
return false;
}
}
else{
return false;
}
}
function checkExtension($imageName){
$ext = getExtension($imageName);
if(strtolower($ext) == "jpg" || strtolower($ext) == "png" || strtolower($ext) == "jpeg" || strtolower($ext) == "gif" || strtolower($ext) == "bmp"){
return true;
}else{
return false;
}
}
function checkByExif($image_tmpName){
if(issetImage($image_tmpName)){
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
$filetype =exif_imagetype($image_tmpName);
if (in_array($filetype, $image_type_allowed)){
return true;
}else{
return false;
}
}else{
return false;
}
}
function checkSize($imageSize){
return ($imageSize<= $GLOBALS["IMAGE_SIZE"] && $imageSize>=1) ? true : false;
}
function changeImageName($imgName){
return md5(pathinfo($imgName, PATHINFO_FILENAME))."_".time();
}
function getExtension($fullImageName){
if($fullImageName)
return pathinfo($fullImageName,PATHINFO_EXTENSION);
}
?>