Upload 類別完整代碼
<?php
class Upload {
private $allowExt = ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'];
private $maxSize = 1; // MB
public function getInfo($flag) {
return $_FILES[$flag] ?? null;
}
public function getExt($filename) {
return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
}
private function checkExt($filename) {
return in_array($this->getExt($filename), $this->allowExt, true);
}
public function checkSize($size) {
return $size < $this->maxSize * 1024 * 1024;
}
public function randName($len = 6) {
$chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
return substr(str_shuffle($chars), 0, $len);
}
public function createDir() {
$dir = './upload/' . date('Y/m/d');
if (is_dir($dir) || mkdir($dir, 0777, true)) {
return $dir;
}
return false;
}
public function uploadFile($flag) {
$file = $this->getInfo($flag);
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
return ['error' => '無檔案上傳或上傳錯誤代碼:' . $file['error']];
}
if (!$this->checkExt($file['name'])) {
return ['error' => '不支援的檔案類型'];
}
if (!$this->checkSize($file['size'])) {
return ['error' => '檔案大小超過限制(' . $this->maxSize . 'MB)'];
}
$filename = $this->randName() . '.' . $this->getExt($file['name']);
$dir = $this->createDir();
if (!$dir) return ['error' => '建立目錄失敗'];
$dest = $dir . '/' . $filename;
if (move_uploaded_file($file['tmp_name'], $dest)) {
return ['filename' => $filename, 'dir' => $dir, 'path' => $dest];
}
return ['error' => '移動檔案失敗'];
}
}
使用範例
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<button type="submit">上傳</button>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$upload = new Upload();
$result = $upload->uploadFile('myfile');
if (isset($result['error'])) {
echo '失敗:' . $result['error'];
} else {
echo "成功!路徑:{$result['path']}";
}
}
?>
安全加強建議
- MIME 類型二次驗證:
finfo_file(finfo_open(FILEINFO_MIME_TYPE), $tmp) 檢查真實 MIME,防止偽造副檔名。
- 圖片重繪:
imagecreatefromjpeg/png/gif 讀取並 imagejpeg() 重寫,剝離潛在惡意代碼。
- 儲存目錄不可執行:Nginx
location /upload { php_flag engine off; }。
- 檔案名稱資料庫記錄:原始檔名、儲存路徑、上傳者、時間存入資料表,便於管理。
- 大檔案分片上傳:前端切片,後端合併,避免超時與記憶體爆炸。