douye1876
2014-09-16 08:41
浏览 38
已采纳

仅允许使用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.

图片转代码服务由CSDN问答提供 功能建议

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

  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“不允许!”; 
 死; 
} 
   
 
 

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhuanqiao5290 2014-09-16 08:46
    已采纳

    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']
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题