|
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// 检查是否为图片
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check === false) {
echo "文件不是图片。";
$uploadOk = 0;
}
// 限制文件大小 (2MB)
if ($_FILES["fileToUpload"]["size"] > 2 * 1024 * 1024) {
echo "文件过大。";
$uploadOk = 0;
}
// 允许的文件格式
if (!in_array($imageFileType, ["jpg", "png", "jpeg", "gif"])) {
echo "仅支持 JPG, JPEG, PNG, GIF 格式。";
$uploadOk = 0;
}
// 上传文件
if ($uploadOk) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "文件 " . htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " 上传成功。";
} else {
echo "上传失败。";
}
}
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
选择图片上传:
<input type="file" name="fileToUpload" required>
<input type="submit" value="上传图片" name="submit">
</form>
</body>
</html> |
|