doujiu8479 2014-04-04 01:15
浏览 40

验证PHP中文件上载的正确方法 - 包括用户更改文件扩展名?

Currently I check all elements of an image in PHP before I allow it to be uploaded. But when it comes to things like file extensions I'm a bit concerned.

I use the following to only allow files of a certain type to be uploaded:

$allowed_ext = array("jpeg", "jpg", "gif", "png");

$tmp_ext = explode(".", $_FILES["file"]["name"]);
$ext = strtolower(end($tmp_ext));

if ((($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/png"))
&& in_array($ext, $allowed_ext)) {
    //Continue
} else {
    //Don't allow
}

But does this prevent all forms of users changing file extensions themselves? e.g. If a user changed the file extension of something malicious to .jpeg or .png - would this prevent it?

I can't find any posts clarifying this, so any help is appreciated!

  • 写回答

2条回答 默认 最新

  • dongxian8858 2014-04-04 01:20
    关注

    Short answer, no, you can't rely on the MIME type. Both the type and the file extension are provided by the client.

    Looks like you can use getimagesize() for verifying an image, credit to this thread: PHP: $_FILES["file"]["type"] is useless

    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统