在PHP中處理文件上傳,通常需要以下幾個(gè)步驟:
enctype
屬性設(shè)置為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腳本,用于處理表單提交的文件。在這個(gè)腳本中,你將檢查是否有文件被上傳,然后將其移動(dòng)到指定的目錄。<?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
的目錄,用于存儲(chǔ)上傳的文件。如果沒有這個(gè)目錄,你需要手動(dòng)創(chuàng)建它,并確保它具有適當(dāng)?shù)淖x寫權(quán)限。現(xiàn)在,當(dāng)用戶通過HTML表單選擇一個(gè)文件并點(diǎn)擊"上傳文件"按鈕時(shí),PHP腳本會(huì)處理文件上傳并將其保存到uploads
目錄中。如果上傳過程中出現(xiàn)任何錯(cuò)誤,用戶將看到相應(yīng)的錯(cuò)誤消息。