Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Created by PhpStorm.
- * User: mac
- * Date: 2018/1/9
- * Time: 21:14
- */
- class Upload
- {
- protected $name;
- protected $allow_size;
- protected $allow_mime;
- protected $allow_ext;
- protected $upload;
- protected $upfile;
- protected $error = null;
- protected $extension;
- protected $newName;
- public function __construct(
- $upload = "./uploads",
- $name = 'pic',
- $allow_size = 3000000,
- $allow_mime = array('image/jpeg', 'image/gif'),
- $allow_ext = array('jpg', 'gif', 'png')
- )
- {
- $this->upload = $upload;
- $this->name = $name;
- $this->allow_size = $allow_size;
- $this->allow_mime = $allow_mime;
- $this->allow_ext = $allow_ext;
- //1,观察数组
- $this->upfile = $_FILES[$this->name];
- //name--type--temp_name--error--size
- }
- //2,判断错误
- public function upFile()
- {
- //观察数组,在构造方法中首先执行
- //判断错误
- $this->judgeError();
- //判断大小
- $this->judgeSize();
- //判断mime
- $this->judgeMime();
- //判断ext
- $this->judgeExt();
- if (is_null($this->error)) {
- //新建目录,文件名
- $this->createDir();
- //8,移动文件
- if (is_uploaded_file($this->upfile['tmp_name'])) {
- $res = move_uploaded_file($this->upfile['tmp_name'], $this->upload . '/' . $this->newName);
- if ($res) {
- $info = array(
- 'name' => $this->upfile['name'],
- 'newname' => $this->newName,
- 'ext' => $this->extension,
- 'mime' => $this->upfile['type'],
- 'size' => $this->upfile['size']
- );
- return $info;
- }
- }
- }
- }
- //3,判断大小
- protected function judgeError()
- {
- if ($this->upfile['error'] > 0) {
- switch ($this->upfile['error']) {
- case 1:
- $this->error = '超出php upload_max_filesize大小';
- return false;
- case 2:
- $this->error = '超出html MAX_FILE_SIZE大小';
- return false;
- case 3:
- $this->error = '只有部分文件';
- return false;
- case 4:
- $this->error = '没有文件上传';
- return false;
- case 6:
- $this->error = '找不到临时文件夹';
- return false;
- case 7:
- $this->error = '临时文件夹不可写';
- return false;
- }
- }
- }
- //4,判断mime类型
- protected function judgeSize()
- {
- if ($this->upfile['size'] > $this->allow_size) {
- $this->error = '文件大小超出了指定范围';
- return false;
- }
- }
- //5,判断扩展名
- protected function judgeMime()
- {
- if (!in_array($this->upfile['type'], $this->allow_mime)) {
- $this->error = 'mime类型不被允许';
- return false;
- }
- }
- protected function judgeExt()
- {
- $this->extension = pathinfo($this->upfile['name'], PATHINFO_EXTENSION);
- if (!in_array($this->extension, $this->allow_ext)) {
- $this->error = '扩展名不允许';
- return false;
- }
- }
- protected function createDir()
- {
- //6,新建目录
- if (!file_exists($this->upload)) {
- mkdir($this->upload, 0755);
- }
- //7,准备随机文件名
- $this->newName = md5(time(), mt_rand()) . '.' . $this->extension;
- }
- public function getError()
- {
- return $this->error;
- }
- }
Add Comment
Please, Sign In to add comment