文件上传类

<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/26
 * Time: 16:29
 */
abstract class aUpLoad
{
    public $allowExt = array('jpg', 'jpeg', 'png', 'rar');
    public $maxSize = 1;//最大上传大小,M为单位
    protected $error = '';//错误信息

    abstract public function getInfo($name);

    abstract public function createDir();

    abstract public function randStr($len = 8);

    abstract public function up($name);

    abstract public function checkType($ext);

    abstract public function checkSize($size);

    public function getError()
    {
        return $this->error;
    }

}

class UpLoad extends aUpLoad
{

    public function getInfo($name)
    {

        return $_FILES[$name];
    }

    public function createDir()
    {
        $dir = 'up/' . date('Y/m', time());
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        return $dir;
    }

    public function randStr($len = 8)
    {
        return md5(time()) . mt_rand(111, 999);
    }

    public function checkType($ext)
    {
        return in_array($ext, $this->allowExt);
    }

    public function checkSize($size)
    {
        return $size < $this->maxSize * 1024 * 1024;
    }

    public function up($name)
    {
        if (!isset($_FILES[$name])) {
            echo '请上传文件';
            exit;
        }

        $info = $this->getInfo($name);
        $ext = ltrim(strrchr($info['name'], '.'), '.');
        if (!$this->checkType($ext)) {
            echo '文件后缀名不正确';
            exit;
        }
        if (!$this->checkSize($info['size'])) {
            echo '文件太大';
            exit;
        }

        $dir = $this->createDir();
        $filename = $this->randStr() . '.' . $ext;
        $path = $dir . '/' . $filename;
        if (move_uploaded_file($info['tmp_name'], $path)) {
            $data['filename'] = $filename;
            return $data;
        }
    }
}

$file = new UpLoad();
$data = $file->up('pic');
var_dump($data);

猜你喜欢

转载自blog.csdn.net/u014230945/article/details/79380366