<?php class Upload { private $error; private $destination; private $fileInfo; private $uploadDir; private $maxFileSize; private $allowExt; private $checkImage; function __construct($fileInfo, $uploadDir = './uploads', $maxFileSize = 1024 * 1024 * 1, $allowExt = array('jpg', 'gif', 'png', 'bmp', 'jpeg'), $checkImage = true, $allowMime = array('image/gif', 'image/jpeg', 'image/png')) { $this->fileInfo = $fileInfo; $this->uploadDir = $uploadDir; $this->maxFileSize = $maxFileSize; $this->allowExt = $allowExt; $this->checkImage = $checkImage; $this->allowMime = $allowMime; } /*** * 處理上傳文件 * @return string */ public function uploadFile() { if (!$this->fileInfo) { $this->error = '文件信息不存在'; return $this->error; } if ($this->checkError() && $this->checkImageType() && $this->checkMaxFileSize() && $this->checkAllowExt() && $this->checkPostUpload() && $this->checkMime() ) { //判斷文件夾是否存在 $this->checkUploadDir(); //生成惟一文件名 $destination = $this->uploadDir . '/' . $this->buildUniqueId() . '.' . $this->getExt(); if (@move_uploaded_file($this->fileInfo['tmp_name'], $destination)) { $this->destination = $destination; return $this->destination; } else { $this->error = '移動上傳文件失敗'; } return $this->error; } return $this->error; } private function checkError() { if ($this->fileInfo['error'] == UPLOAD_ERR_OK) { return true; } $this->error = '上傳出現錯誤,錯誤代碼:' . $this->fileInfo['error']; return false; } private function buildUniqueId() { return md5(uniqid(microtime(true), true)); } private function checkUploadDir() { if (!file_exists($this->uploadDir)) { mkdir($this->uploadDir, 0777, true); chmod($this->uploadDir, 0777); } } private function checkAllowExt() { if (in_array($this->getExt(), $this->allowExt)) { return true; } $this->error = '該類型的文件不能上傳'; return false; } private function checkMaxFileSize() { if ($this->maxFileSize > $this->fileInfo['size']) { return true; } $this->error = '上傳文件的大小已超過限額'; return false; } private function checkImageType() { if ($this->checkImage) { if ($this->checkAllowExt() && getimagesize($this->fileInfo['tmp_name'])) { return true; } $this->error = '上傳的不是圖片'; return false; } return true; } private function checkPostUpload() { if (is_uploaded_file($this->fileInfo['tmp_name'])) { return true; } $this->error = '不是Post上傳的文件'; return false; } private function checkMime() { if (in_array($this->getMime(), $this->allowMime)) { return true; } $this->error = 'Mime類型不正確'; return false; } private function getMime() { if ($imageInfo = getimagesize($this->fileInfo['tmp_name'])) { return $imageInfo['mime']; } return false; } private function getExt() { return strtolower(pathinfo($this->fileInfo['name'], PATHINFO_EXTENSION)); } }