<?php
// 1. 實例化傳輸適配器 (預設 HTTP POST $_FILES)
$upload = new Zend_File_Transfer();
// 2. 加入驗證器鏈
$upload->addValidator('Size', false, 5 * 1024 * 1024); // 最大 5MB
$upload->addValidator('Extension', false, 'jpg,gif,png'); // 允許副檔名
$upload->addValidator('MimeType', false, 'image/jpeg,image/gif,image/png'); // 建議加 MIME
$upload->addValidator('ImageSize', false, [ // 可選:圖片尺寸限制
'minwidth' => 10, 'minheight' => 10,
'maxwidth' => 2000, 'maxheight' => 2000
]);
// 3. 驗證
if (!$upload->isValid()) {
$messages = $upload->getMessages();
// 回傳 JSON 錯誤或顯示表單錯誤
echo json_encode(['success' => false, 'errors' => $messages]);
exit;
}
// 4. 取得上傳檔案資訊
$fileInfo = $upload->getFileInfo(); // ['form_field_name' => [...]]
$fieldName = 'pic'; //
$originalName = $fileInfo[$fieldName]['name'];
$tmpName = $fileInfo[$fieldName]['tmp_name'];
// 5. 解析副檔名
$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
// 或使用類別方法
$ext = $this->getExtension($originalName);
// 6. 產生儲存目錄 (按日期分目錄)
$dir = './upload' . date('/Y/m/d/');
// 7. 產生唯一檔名 (時間 + 隨機數)
do {
$filename = date('His') . rand(100000, 999999) . '.' . $ext;
} while (file_exists($dir . $filename));
// 8. 確保目錄存在
$this->makeDir($dir); // 遞迴建立、權限 0777
// 9. 設定目的地 + 重命名過濾器
$upload->setDestination($dir);
$upload->addFilter('Rename', [
'target' => $dir . $filename, // 完整目標路徑
'overwrite' => true
]);
// 10. 接收 (實際移動檔案)
if (!$upload->receive()) {
echo json_encode(['success' => false, 'msg' => '上傳失敗']);
exit;
}
echo json_encode(['success' => true, 'filename' => $filename, 'path' => $dir . $filename]);
// 取得副檔名
public function getExtension(string $fileName): string
{
if (!$fileName) return '';
$exts = explode('.', $fileName);
return strtolower(end($exts));
}
// 建立目錄 (跨平台編碼處理)
public function makeDir(string $path): bool
{
if (DIRECTORY_SEPARATOR === '\\') { // Windows
$path = iconv('UTF-8', 'GBK//IGNORE', $path);
}
if (!$path) return false;
if (is_dir($path)) return true;
return mkdir($path, 0777, true); // 遞迴建立
}
| ZF1 | Laminas (ZF 繼任) | Symfony | Laravel |
|---|---|---|---|
| `Zend_File_Transfer` | `Laminas\Http\PhpEnvironment\Request::getFiles()` + `Laminas\Validator\File\*` | `UploadedFile` + `Validator\File\*` | `$request->file('pic')` + `Store` + `Validation` Rule |
| `addValidator('Size')` | `Laminas\Validator\File\Size` | `File\MaxSize` | `File::max(5120)` (KB) |
| `addValidator('Extension')` | `Laminas\Validator\File\Extension` | `File\Extension` | `File::extensions(['jpg','png'])` |
| `addFilter('Rename')` | `Laminas\Filter\File\Rename` | 手動 `move()` | `$file->storeAs('uploads', $name)` |
| `setDestination()` | 同上 | 同上 | `filesystems.php` disks 設定 |
ZF1 `Zend_File_Transfer` 提供 **驗證器鏈 + 過濾器鏈 + 適配器** 的靈活架構。核心流程:`addValidator` → `isValid` → `getFileInfo` → `setDestination` + `addFilter('Rename')` → `receive()`。維護舊專案時請務必補上 MIME 驗證、目錄執行權限隔離;新專案請直接採用 **Laminas、Symfony HttpFoundation、Laravel Filesystem** 等現代元件。