美文网首页
[PHP文件上传下载]③--服务端限制

[PHP文件上传下载]③--服务端限制

作者: 子木同 | 来源:发表于2017-09-18 16:20 被阅读20次
    Paste_Image.png
    <?php
    //getimagesize($filename):得到指定图片的信息,
    //如果是图片返回数组 如果不是图片返回FALSE
    $filename = 'uploads/yun.jpeg';
    var_dump(getimagesize($filename));
    /*
     * array
      0 => int 224
      1 => int 224
      2 => int 2
      3 => string 'width="224" height="224"' (length=24)
      'bits' => int 8
      'channels' => int 3
      'mime' => string 'image/jpeg' (length=10)
     */
    
    ?>
    
    <html>
    <head><title></title></head>
    <body>
    <form action="doAction.php" method="post" enctype="multipart/form-data">
        请选择您要上传的文件:
        <input type="file" name="myFile">
        <input type="submit" value="上传文件">
    </form>
    </body>
    </html>
    

    doAction.php

    <?php
    $fileInfo = $_FILES['myFile'];
    $maxSize = 2097152;//2M 允许的最大值
    $allowExt = array('jpeg', 'jpg', 'png', 'gif', 'wbmp');
    $flag = true;//检测是否为真实的图片类型
    //1.判断错误号
    if ($fileInfo['error'] == 0) {
        //判断上传文件的大小
        if ($fileInfo['size'] > $maxSize) {
            exit("上传文件过大");
        }
        //$ext=strtolower(end(explode('.',$fileInfo['name'])))
        $ext = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
        if (!in_array($ext, $allowExt)) {
            exit("非法文件类型");
        }
        //判断是否是通过HTTP POST文件上传上来的
        if (!is_uploaded_file($fileInfo['tmp_name'])) {
            exit('文件不是通过HTTP POST 方式上传来的');
        }
        //检测是否为真实的图片类型
        if ($flag) {
            if (!getimagesize($fileInfo['tmp_name'])) {
                exit('不是真正的图片类型');
            }
        }
        $path = 'uploads';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
            chmod($path, 0777);
        }
        //确保文件名唯一,防止重名产生覆盖
        $uniName = md5(uniqid(microtime(true), true)) . '.' . $ext;
        $destination = $path . '/' . $uniName;//uploads/e8b67f2be200f625ef111b4f3352903b.jpeg
        if (@move_uploaded_file($fileInfo['tmp_name'], $destination)) {
            echo "文件上传成功";
        } else {
            echo "文件上传失败";
        }
    } else {
        switch ($fileInfo['error']) {
            case 1:
                echo "上传文件超过了PHP配置文件中upload_max_file";
                break;
            case 2:
                echo "超过了表单MAX_FILE_SIZE";
                break;
            case 3:
                echo "文件部分被上传";
                break;
            case 4:
                echo "没有选择上传文件";
                break;
            case 6:
                echo "没有找到临时目录";
                break;
            case 7:
            case 8:
                echo "系统错误";
                break;
        }
    }
    
    ?>
    
    Paste_Image.png Paste_Image.png

    相关文章

      网友评论

          本文标题:[PHP文件上传下载]③--服务端限制

          本文链接:https://www.haomeiwen.com/subject/adrbsxtx.html