PHP 內建 move_uploaded_file() 函式可將暫存檔案移動到指定目錄,是實作檔案上傳的關鍵。上傳流程:表單 enctype="multipart/form-data" → $_FILES 取得暫存路徑 → 移動到永久儲存位置。
<?php
$tmpName = $_FILES['myupload']['tmp_name'];
$destPath = '/path/to/dest/' . $_FILES['myupload']['name'];
if (!move_uploaded_file($tmpName, $destPath)) {
echo 'An error has occurred moving the uploaded file.<br>';
echo 'Please ensure that if safe_mode is on that the UID PHP is using matches the file.';
exit;
} else {
echo 'The file has been successfully uploaded!';
}
?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="myupload">
<input type="submit" value="上傳">
</form>
file_uploads = On、upload_max_filesize、post_max_size 需符合需求。生產環境建議:
$_FILES['myupload']['error'] 判斷上傳狀態(UPLOAD_ERR_OK 為 0)。pathinfo() 擷取副檔名,配合白名單驗證。