Zend Framework 1(ZF1)的 Zend_File_Transfer 元件提供物件導向的檔案上傳處理,內建驗證器與過濾器可輕鬆完成大小限制、副檔名檢查、自動重命名、日期目錄建立等常見需求。
// 1. 實例化上傳物件
$upload = new Zend_File_Transfer();
// 2. 加入驗證器:限制 5MB、僅允許 jpg/gif/png
$upload->addValidator('Size', false, 5 * 1024 * 1024);
$upload->addValidator('Extension', false, 'jpg,gif,png');
if (!$upload->isValid()) {
print '檔案大小或格式不符合';
exit();
}
// 3. 取得上傳檔案資訊(表單 name="pic")
$fileInfo = $upload->getFileInfo();
$ext = $this->getExtension($fileInfo['pic']['name']);
// 4. 產生日期目錄 ./upload/2024/05/20/
$dir = './upload' . date('/Y/m/d/');
// 5. 產生唯一檔名:時分秒 + 6位隨機數
do {
$filename = date('His') . rand(100000, 999999) . '.' . $ext;
} while (file_exists($dir . $filename));
// 6. 確保目錄存在
$this->makeDir($dir);
// 7. 設定儲存目的地與重命名過濾器
$upload->setDestination($dir);
$upload->addFilter('Rename', array('target' => $filename, 'overwrite' => true));
// 8. 執行接收(實際搬移檔案)
if (!$upload->receive()) {
print '上傳圖片失敗';
exit();
}
print $filename; // 回傳最終檔名供前端使用
/**
* 取得檔案副檔名
* @param string $fileName
* @return string
*/
public function getExtension($fileName) {
if (!$fileName) return '';
$exts = explode('.', $fileName);
return end($exts);
}
/**
* 建立多層目錄
* @param string $path
* @return bool
*/
public function makeDir($path) {
if (DIRECTORY_SEPARATOR == '\\') { // Windows
$path = iconv('utf-8', 'gbk', $path);
}
if (!$path) return false;
if (file_exists($path)) return true;
return mkdir($path, 0777, true);
}
addValidator() 可鏈式呼叫,支援 Size、Extension、MimeType、ImageSize 等。addFilter('Rename', ...) 會在 receive() 時自動改名,overwrite => true 避免同名衝突報錯。iconv() 處理,避免中文目錄建立失敗。此範例適用於 ZF1 專案快速落地檔案上傳功能,若為 Zend Framework 3 / Laminas,請改用 Laminas\Http\PhpEnvironment\Request 搭配 Laminas\Filter\File\RenameUpload 等新元件。