[PHP文件上传下载]④--单文件上传函数的封装

upload.func.php

<?php
function uploadFile($fileInfo, $uploadPath = 'uploads', $flag = true,
                    $allowExt = array('jpeg', 'jpg', 'png', 'gif'),
                    $maxSize = 2097152)
{
    //判断错误号
    if ($fileInfo['error'] > 0) {
        $mes = '';
        switch ($fileInfo['error']) {
            case 1:
                $mes = "上传文件超过了PHP配置文件中upload_max_file";
                break;
            case 2:
                $mes = "超过了表单MAX_FILE_SIZE";
                break;
            case 3:
                $mes = "文件部分被上传";
                break;
            case 4:
                $mes = "没有选择上传文件";
                break;
            case 6:
                $mes = "没有找到临时目录";
                break;
            case 7:
            case 8:
                $mes = "系统错误";
                break;
        }
        exit($mes);
    } else {
        $ext = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
        //检测文件上传的类型
        if (!in_array($ext, $allowExt)) {
            exit("非法文件类型");
        }

        //检测文件大小是否符合规范
        if ($fileInfo['size'] > $maxSize) {
            exit('上传文件过大');
        }
        //检测图片是否为真实的图片类型
        if ($flag) {
            if (!getimagesize($fileInfo['tmp_name'])) {
                exit('不是真实的图片类型');
            }
        }
        //检测是否是通过HTTP POST 方式上传的
        if (!is_uploaded_file($fileInfo['tmp_name'])) {
            exit('文件不是通过HTTP POST方式上传上来的');
        }

        if (!file_exists($uploadPath)) {
            mkdir($uploadPath, 0777, true);
            chmod($uploadPath, 0777);
        }
        $uniName = md5(uniqid(microtime(true), true)) . '.' . $ext;
        $destination = $uploadPath . '/' . $uniName;
        if (!@move_uploaded_file($fileInfo['tmp_name'], $destination)) {
            exit("文件移动失败");
        }

        return array(
            'newName' => $destination,
            'size' => $fileInfo['size'],
            'type' => $fileInfo['type']
        );

        //return $destination;
    }
}

?>
<html>
<head><title></title></head>
<body>
<form action="doAction.php" method="post" enctype="multipart/form-data">
    请选择您要上传的文件:
    <input type="file" name="myFile"><br/>
    <input type="submit" value="上传文件">
</form>
</body>
</html>

doAction.php

<?php
require 'upload.func.php';
$fileInfo = $_FILES['myFile'];
$allowExt = array('jpeg', 'jpg', 'png', 'gif', 'html', 'txt');
$newName = uploadFile($fileInfo, 'imooc', false, $allowExt);
var_dump($newName);

?>
Paste_Image.png
Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容