在PHP中,要限制上傳文件的類型,可以通過檢查文件的MIME類型和擴展名來實現。以下是一個簡單的示例:
<!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
// 允許的文件類型
$allowed_types = array('image/jpeg', 'image/png', 'image/gif');
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
if (isset($_POST['submit'])) {
$temp_file = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$file_extension = pathinfo($_FILES['fileToUpload']['name'], PATHINFO_EXTENSION);
// 檢查文件類型
if (!in_array($file_type, $allowed_types) || !in_array($file_extension, $allowed_extensions)) {
echo "Sorry, only JPEG, PNG, and GIF files are allowed.";
} else {
// 如果文件類型合法,將其移動到指定目錄
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($temp_file, $target_file)) {
echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
在這個示例中,我們只允許JPEG、PNG和GIF文件上傳。你可以根據需要修改$allowed_types
和$allowed_extensions
數組來允許其他文件類型。注意,這種方法僅檢查客戶端提供的MIME類型和擴展名,這可能會受到惡意用戶的影響。因此,始終確保在服務器端進行進一步的驗證和安全措施。