美文网首页
php-file-upload

php-file-upload

作者: _不能说的秘密i | 来源:发表于2019-04-19 09:17 被阅读0次
    /**
     * 上传文件
     *
     * @param $file
     */
    public function uploadFile($fileinfo)
    {
        // 获取文件上传配置
        $cfg = [
          'allow_type' => ['jpg', 'png', 'gif'],
          'max_size' => 1024 * 1024 * 5
        ];

        $fileName = $fileinfo['name'];

        // 判断文件后缀名
        $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
        if (!in_array($fileExt, $cfg['allow_type'])) {
            return ['status' => false, 'message' => '不允许该类型的文件'];
        }

        // 判断文件大小
        if ($fileinfo['size'] > $cfg['max_size']) {
            return ['status' => false, 'message' => '文件过大'];
        }

        // 判断是否是通过http请求上传的文件
        if (is_uploaded_file($fileName)) {
            return ['status' => false, 'message' => '非法上传'];
        }

        // 按天生成文件夹, 生成随机文件名
        $cfgPath = trim($cfg['save_path'], '/').'/'.date('Ymd');
        $savePath = rtrim(str_replace('\\', '/', ROOT_PATH), '/').'/public/'.$cfgPath;
        if (!file_exists($savePath)) {
            mkdir($savePath, 0777);
        }

        // 上传文件
        $fileName = md5(time().mt_rand(0, 9999)).'.'.$fileExt;
        if (move_uploaded_file($fileinfo['tmp_name'], $savePath.'/'.$fileName)) {
            return ['status' => true, 'message' => '上传成功', 'path' => $cfgPath.'/'.$fileName];
        } else {
            return ['status' => false, 'message' => '上传失败'];
        }

    }

相关文章

网友评论

      本文标题:php-file-upload

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