Blogger Information
Blog 32
fans 2
comment 2
visits 23305
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【Part1】单个/多个文件上传处理(0219)
暴风战斧
Original
857 people have browsed it

【1、单个文件上传】

<?php

namespace day19;

use Exception;

// 处理用户文件上传,三步操作

/**
 * 1.判断文件是否上传成功?
 * 2.判断临时文件是否合法?
 * 3.将临时文件移动到用户目录中
 */

try {
    // 1、判断文件是否上传成功?
    $errorCode = $_FILES['user_doc']['error'];
    if ($errorCode > UPLOAD_ERR_OK) {
        switch ($errorCode) {
            case UPLOAD_ERR_INI_SIZE:
                throw new Exception('上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值');
                break;
            case UPLOAD_ERR_FORM_SIZE:
                throw new Exception('上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值');
                break;
            case UPLOAD_ERR_PARTIAL:
                throw new Exception('文件只有部分被上传');
                break;
            case UPLOAD_ERR_NO_FILE:
                throw new Exception('没有文件被上传');
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                throw new Exception('找不到临时文件夹');
                break;
            case UPLOAD_ERR_CANT_WRITE:
                throw new Exception('文件写入失败');
                break;
            default:
                throw new Exception('未知类型错误');
        }
    }
    // 2、判断临时文件是否合法?
    $tmpFile = $_FILES['user_doc']['tmp_name'];

    // 限制:仅允许上传图片类型的文件
    $allowFileTypes = ['pdf'];

    // is_uploaded_file:检验文件合法性
    if (true === is_uploaded_file($tmpFile)) {
        // 获取上传文件的扩展名
        $extension = pathinfo($_FILES['user_doc']['name'])['extension'];
        if (in_array($extension, $allowFileTypes)) {
            // 目标文件名
            $destName = 'uploads/' . md5($FILES['user_doc']['name']) . time() . '.' . $extension;
            // 3、将临时文件移动到用户目录中
            if (move_uploaded_file($tmpFile, $destName)) {
                echo '<script>alert("上传成功");location.href="form1.html";</script>';
            }
        } else {
            throw new Exception('文件类型错误');
        }
    } else {
        throw new Exception('非法操作');
    }

} catch (Exception $e) {
    echo $e->getMessage();
}

01.png

02.png

03.png

04.png

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:可以试试自己动手封装一个上传类
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments