在PHP中處理文件上傳,通常需要以下幾個步驟:
enctype
屬性設置為multipart/form-data
,這是處理文件上傳所必需的。<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
upload.php
的PHP腳本,用于處理表單提交的文件。在這個腳本中,你將檢查是否有文件被上傳,然后將其移動到指定的目錄。<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
uploads
的目錄,用于存儲上傳的文件。如果沒有這個目錄,你需要手動創建它,并確保它具有適當的讀寫權限。現在,當用戶通過HTML表單選擇一個文件并點擊"上傳文件"按鈕時,PHP腳本會處理文件上傳并將其保存到uploads
目錄中。如果上傳過程中出現任何錯誤,用戶將看到相應的錯誤消息。