method="post" enctype="multipart/form-data" + input type="file"。$_FILES,驗證錯誤碼、大小、類型、真實性。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。function uploadFile($fileInfo, $path, $allowExt, $maxSize) { ... }
function getFiles() { ... } // 將 $_FILES 統一轉為單檔結構陣列
foreach (getFiles() as $fileInfo) { uploadFile($fileInfo); }
return ['mes' => '訊息', 'dest' => '路徑']; // 成功或失敗均返回,不中斷流程
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、臨時檔案生命週期readfile() 輸出流