首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Zend Framework 1 文件上傳完整實作範例(含驗證、重命名、目錄自動建立)

     編輯:PHP 相關知識

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);
}

輔助方法:遞迴建立目錄(相容 Windows 編碼)

/**
 * 建立多層目錄
 * @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 避免同名衝突報錯。
  • Windows 下路徑編碼問題需以 iconv() 處理,避免中文目錄建立失敗。
  • 實務上建議將上傳邏輯封裝為 Service Class,搭配異常處理、日誌記錄、資料庫寫入檔案資訊。

此範例適用於 ZF1 專案快速落地檔案上傳功能,若為 Zend Framework 3 / Laminas,請改用 Laminas\Http\PhpEnvironment\Request 搭配 Laminas\Filter\File\RenameUpload 等新元件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved