📅  最后修改于: 2023-12-03 15:27:40.474000             🧑  作者: Mango
如何处理PHP中的文件上传?
在PHP中,可以使用$_FILES
全局变量来处理文件上传,具体步骤如下:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
$target_dir = "uploads/"; // 上传文件保存的目录
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); // 上传文件的完整路径
$uploadOk = 1; // 标识文件是否上传成功
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // 获取上传文件的扩展名
// 判断是否是真实图片
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// 判断文件是否已经存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// 判断文件大小
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// 允许上传的文件类型
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 判断文件是否上传成功
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// 如果都符合要求,则上传文件
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
$target_dir
为上传文件的保存目录,可以根据需要自定义。basename($_FILES["fileToUpload"]["name"])
获取上传文件的原始文件名。strtolower(pathinfo($target_file,PATHINFO_EXTENSION))
获取上传文件的扩展名,将扩展名转为小写方便比较。$check = getimagesize($_FILES["fileToUpload"]["tmp_name"])
判断上传的文件是否为真实图片,可以避免非图片被误认为图片。$_FILES["fileToUpload"]["size"]
获取上传文件大小。$imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif"
设置允许上传的文件类型。move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
将上传文件移动到目标目录。upload_max_filesize
,上传文件个数限制max_file_uploads
等。