要使用PHP進行文件上傳處理,請遵循以下步驟:
首先,創建一個簡單的HTML表單,允許用戶選擇要上傳的文件。請確保將enctype
屬性設置為multipart/form-data
,以便正確上傳文件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload with PHP</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select a file to upload:
<input type="file" name="uploaded_file">
<br><br>
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
接下來,創建一個名為upload.php
的PHP文件,該文件將處理表單提交的文件。在這個文件中,我們將檢查文件大小、類型等,然后將其移動到服務器上的目標目錄。
<?php
// Define the target directory
$target_dir = "uploads/";
// Get the uploaded file information
$file_name = basename($_FILES["uploaded_file"]["name"]);
$file_size = $_FILES["uploaded_file"]["size"];
$file_type = $_FILES["uploaded_file"]["type"];
$file_tmp_name = $_FILES["uploaded_file"]["tmp_name"];
// Check if the file is a valid image
$image_check = getimagesize($file_tmp_name);
if ($image_check !== false) {
echo "File is an image - " . $image_check["mime"] . ".";
} else {
echo "File is not an image.";
exit;
}
// Check if the file is too large
if ($file_size > 5 * 1024 * 1024) {
echo "File is too large. Please upload files smaller than 5MB.";
exit;
}
// Check if the file type is allowed
$allowedTypes = array("image/jpeg", "image/png", "image/gif");
if (!in_array($file_type, $allowedTypes)) {
echo "Invalid file type. Please upload JPEG, PNG, or GIF files.";
exit;
}
// Generate a unique file name
$unique_file_name = uniqid("", true) . "_" . $file_name;
// Move the file to the target directory
if (move_uploaded_file($file_tmp_name, $target_dir . $unique_file_name)) {
echo "File uploaded successfully: " . $unique_file_name;
} else {
echo "Error uploading file. Please try again.";
}
?>
在服務器上創建一個名為uploads
的目錄,用于存儲上傳的文件。確保該目錄具有適當的讀寫權限。
現在,當用戶通過HTML表單上傳文件時,upload.php
腳本將處理文件上傳并將其保存到uploads
目錄中。