douyi6168 2012-10-28 11:37
浏览 17
已采纳

上传验证,允许其他扩展?

At the moment I have allowed for .jpg files to be uploaded.

How do I add jpeg, gif and png?

My current code is as follows...

$filename = basename($_FILES['photo']['name']);
            $ext = substr($filename, strrpos($filename, '.') + 1);

            //Check if the file is JPEG image and it's size is less than 5Mb
$allowedExts = array('jpg', 'jpeg', 'gif', 'png');
            if ( (in_array($ext, $allowedExts)) && ($_FILES["photo"]["type"] == "image/jpeg") && ($_FILES["photo"]["size"] <= 5242880) ){
                //Determine the path to which we want to save this file
                $newname = str_replace( ' ', '_', trim( strip_tags( $_POST['name'] ) ) ) . _ . $formKey->generateKey() . '_' . time() . '.jpg';
  • 写回答

2条回答 默认 最新

  • douqiju2520 2012-10-28 11:44
    关注

    Make an array of allowed extensions, and check against it. Take a look at http://php.net/manual/en/function.in-array.php.

    You'd end with something like:

    $allowedExts = array('jpg', 'jpeg', 'gif'); // Add more here
    if (in_array($ext, $allowedExts))
    {
        // Do something here
    }
    

    Also, to check the extension of a file, I suggest you to use pathinfo: http://php.net/manual/en/function.pathinfo.php Some people can trick you with uploading files ending with .jpg, but that could be .php files.

    [EDIT] Updated as I hate the mini-commenting:

       $allowedExtensions = array("image/jpeg", "image/png", "image/gif", "image/pjpeg", "image/jpg");
       $pathInfo = pathinfo($_FILES["photo"]["type"]);
       if (in_array($pathInfo['extension'], $allowedExtensions))
       {
           // Do stuff
       }
    

    Waaaay simpler this way. This can even be simplified by using pathinfo's second parameter, but I'm assuming you'll need the other elements of the array after.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错