仅允许使用PHP将图像文件上载到我的服务器

仅允许使用PHP将图像文件上载到我的服务器

问题描述:

I'm trying to make a script in which I only allow .png, .jpeg and .gif files to be uploaded, based on MIME types. What I have so far is this:

if(file_exists($root."/upload/gallery/".$_FILES["image"]["name"]))
{
    $filename = explode(".",$_FILES['image']['name']);
    $randomnumber = rand(0, 10000);
    $imageName = $filename[0].$randomnumber.".".$filename[1];
}
else
{
    $imageName = $_FILES['image']['name'];
}

$image = mysql_real_escape_string(htmlspecialchars("/upload/gallery/".$imageName));

$allowed = array('image/jpeg', 'image/png', 'image/gif');

if(in_array($_FILES['image']['name'], $allowed)){
    echo "Allowed!";
    die;
}
else {
    echo "Not allowed!";
    die;
}

I was almost certain this should work. But it always echoes Not allowed! while I choose files with the correct MIME type, what am I doing wrong here? The code includes a check for files in my upload folder that already have the same name and if so adds a random number to the filename.

我正在尝试创建一个脚本,我只允许.png,.jpeg和.gif文件 上传,基于MIME类型。 到目前为止我所拥有的是: p>

  if(file_exists($ root。“/ upload / gallery /".$_ FILES [”image“] [”name“])  )
 {
 $ filename = explode(“。”,$ _ FILES ['image'] ['name']); 
 $ randomnumber = rand(0,10000); 
 $ imageName = $ filename [0  ]。$ randomnumber。“。”。$ filename [1]; 
} 
else 
 {
 $ imageName = $ _FILES ['image'] ['name']; 
} 
 
 $ image  = mysql_real_escape_string(htmlspecialchars(“/ upload / gallery /".$ imageName)); 
 
 $ allowed = array('image / jpeg','image / png','image / gif'); 
 
if  (in_array($ _ FILES ['image'] ['name'],$ allowed)){
 echo“Allowed!”; 
 die; 
} 
else {
 echo“不允许!”; 
 死; 
} 
  code>  pre> 
 
 

我几乎可以肯定这应该有效。 但它总是回应不允许! code>,而我选择具有正确MIME类型的文件,我在这里做错了什么? 该代码包括检查我的上传文件夹中已经具有相同名称的文件,如果是这样,则在文件名中添加一个随机数。 p> div>

You are comparing the allowed list against the file name, not the type.

The type of the file will be contained in an array of applicable types in:

$_FILES['image']['type']