在Debian系统中处理PHP文件上传,你需要遵循以下步骤:
sudo apt-get update
sudo apt-get install php php-cli php-fpm
/etc/php/{version}/fpm/php.ini或/etc/php/{version}/cli/php.ini文件(将{version}替换为你的PHP版本号),设置以下参数以允许文件上传:file_uploads = On
upload_max_filesize = 50M
post_max_size = 50M
这里,file_uploads设置为On以启用文件上传,upload_max_filesize和post_max_size设置允许上传的最大文件大小。根据需要调整这些值。
sudo systemctl restart php{version}-fpm
upload.html,并添加一个文件上传表单:<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php的PHP文件,用于处理文件上传:<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is an actual image or fake image
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;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 50000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$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 ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
这个脚本会检查上传的文件是否为图像,是否已存在,文件大小是否超过限制以及允许的文件类型。如果所有条件都满足,文件将被上传到uploads/目录。
upload.html文件,选择一个文件并点击上传按钮。如果一切正常,你应该看到文件已成功上传的消息。注意:出于安全原因,请确保在生产环境中对上传的文件进行适当的验证和处理。