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

PHP 檔案上傳下載實戰總結:從入門到物件導向封裝

     編輯:PHP 相關知識

一、上傳核心三步驟

  1. 前端表單:method="post" enctype="multipart/form-data" + input type="file"。
  2. PHP 接收 $_FILES,驗證錯誤碼、大小、類型、真實性。
  3. move_uploaded_file() 移動臨時檔案至永久目錄,生成唯一檔名防覆蓋。

二、關鍵驗證邏輯

  • 錯誤碼:UPLOAD_ERR_OK (0) 成功,1~8 對應超過限制、部分上傳、無檔案、無臨時目錄等。
  • 伺服器配置:upload_max_filesize、post_max_size、max_file_uploads、memory_limit。
  • 安全檢查:
    • 副檔名白名單 in_array($ext, $allowExt)。
    • is_uploaded_file() 確認 HTTP POST 上傳。
    • getimagesize() 驗證真實圖片防偽裝木馬。
    • 唯一檔名:md5(uniqid(microtime(true), true)) . '.' . $ext。

三、函數封裝演進

版本 1:基礎單檔函數

function uploadFile($fileInfo, $path, $allowExt, $maxSize) { ... }

版本 2:多檔支援(降維遍歷)

function getFiles() { ... } // 將 $_FILES 統一轉為單檔結構陣列
foreach (getFiles() as $fileInfo) { uploadFile($fileInfo); }

版本 3:回傳結構化結果,避免 exit 中斷

return ['mes' => '訊息', 'dest' => '路徑']; // 成功或失敗均返回,不中斷流程

四、物件導向 Upload 類

class Upload {
    protected $fileName, $maxSize, $allowMime, $allowExt, $uploadPath, $imgFlag;
    protected $fileInfo, $error, $ext;

    public function __construct($fileName='myFile', $uploadPath='./uploads', $imgFlag=true,
                                $maxSize=5242880, $allowExt=['jpeg','jpg','png','gif'],
                                $allowMime=['image/jpeg','image/png','image/gif']) { ... }

    protected function checkError() { ... }
    protected function checkSize() { ... }
    protected function checkExt() { ... }
    protected function checkMime() { ... }
    protected function checkTrueImg() { ... }
    protected function checkHTTPPost() { ... }
    protected function checkUploadPath() { ... }
    protected function getUniName() { ... }

    public function uploadFile() {
        if ($this->checkError() && $this->checkSize() && $this->checkExt()
            && $this->checkMime() && $this->checkTrueImg() && $this->checkHTTPPost()) {
            $this->checkUploadPath();
            $this->destination = $this->uploadPath . '/' . $this->getUniName() . '.' . $this->ext;
            if (@move_uploaded_file($this->fileInfo['tmp_name'], $this->destination)) {
                return $this->destination;
            }
            $this->error = '移動失敗';
        }
        exit('' . $this->error . '');
    }
}

使用:$u = new Upload('myFile1', 'imooc'); echo $u->uploadFile();

五、檔案下載

<?php
$filename = $_GET['filename'];
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($filename));
readfile($filename);
?>

HTML:<a href="doDownload.php?filename=1.jpg">下載</a>

六、知識清單

  • 表單雙關鍵屬性、$_FILES 結構、降維處理
  • move_uploaded_file vs copy、臨時檔案生命週期
  • 副檔名提取、唯一檔名生成、真實圖片驗證
  • 函數封裝 → 多檔遍歷 → 結構化回傳 → 物件導向重構
  • 下載核心 Header、readfile() 輸出流
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved