如何阻止名为filename.php.jpg的文件上载

如何阻止名为filename.php.jpg的文件上载,php,file-upload,Php,File Upload,所以我有这个脚本来上传文件,是的,我知道它不安全。然而,我现在的问题是我可以上传名为filename.php.jpg的文件。那么我怎样才能防止像theese这样的文件上传呢?我使用了其他东西来阻止php文件被执行 <?php $maindir = "../alla_bilder/images/"; $maindir_th = "../alla_bilder/images/thumbs/"; $uploaddir = "images/"; $uploaddir_th = "images/th

所以我有这个脚本来上传文件,是的,我知道它不安全。然而,我现在的问题是我可以上传名为filename.php.jpg的文件。那么我怎样才能防止像theese这样的文件上传呢?我使用了其他东西来阻止php文件被执行

<?php
$maindir = "../alla_bilder/images/";
$maindir_th = "../alla_bilder/images/thumbs/";
$uploaddir = "images/";
$uploaddir_th = "images/thumbs/";
$allowed = array('jpg','jpeg','png');
$notallowed = array('php');
$uploadOk = 1;
$max_size = 5048 * 1024;

while (list ($key, $val) = each ($_FILES))
{
if ($_FILES[$key]['size'] <= $max_size)     
{
  $file_ext  = pathinfo($_FILES[$key]['name'],PATHINFO_EXTENSION);
  $file_name = basename($_FILES[$key]['name'],'.'.$file_ext);
  if (in_array(strtolower($file_ext),$allowed))       
  {
     $name = $_FILES[$key]['name'];
     $x = 1;
     while (file_exists($uploaddir.'/'.$name)) 
     {
        $name = $file_name.'['.$x.'].'.$file_ext;
        $x++;
     }
     $name = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 22)), 0, 22). '.' .mb_strtolower ($file_ext);
     if (move_uploaded_file($_FILES[$key]['tmp_name'],$uploaddir.'/'.$name))
     {
        chmod($uploaddir.'/'.$name, 0644);
     }
     else
     {
        die(error_get_last());
     }
  }
  else
  {
     die("Invalid file type");
  }
}
else
{
  die("File size too big");
}
copy($uploaddir.'/'.$name, $maindir.'/'.$name);

  $images = glob("images/thumbs/*.*");  
  foreach($images as $image)  
  {  
       $output .= '<div class="col-md-2" align="center" ><img src="' . $image .'" width="200px" height="140px" style="border:1px solid #ccc;" /></div>';  
  }  

//thumbnail image making part
    $modwidth = 200;
    $modheight = 140;

    list($width, $height) = getimagesize($uploaddir.'/'.$name);               
    $ratio_orig = $width/$height;                 
    if ($width/$height > $ratio_orig)
    {         
    $width = $height*$ratio_orig;         
    } else {         
    $height = $width/$ratio_orig;         
    }          
    $tn = imagecreatetruecolor($modwidth, $modheight);
    //$image = imagecreatefromjpeg($uploaddir.'/'.$name);
    $image = imagecreatefromstring(file_get_contents($uploaddir.'/'.$name));
    imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
    imagejpeg($tn, $uploaddir_th.'/'.$name); 
    imagejpeg($tn, $maindir_th.'/'.$name); 

}
echo "STOP!";
?>
看一看finfo扩展,它允许您在操作系统级别嗅探文件类型时确定真正的文件类型

由于finfo是一个扩展,因此需要安装并启用它

实例
 $path = $_FILES[$key]['tmp_name'],$uploaddir.'/'.$name;
 $finfo = finfo_open(FILEINFO_MIME_TYPE);
 $whitelist = array('image/jpg');

 if (in_array(finfo_file($finfo, $path), $whitelist) && move_uploaded_file($path))
 {
    chmod($uploaddir.'/'.$name, 0644);
 }