在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版本号),设置文件上传的大小限制和其他相关选项。例如:upload_max_filesize = 10M
post_max_size = 10M
file_uploads = On
/etc/apache2/sites-available/000-default.conf
文件,添加或修改以下内容:<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
如果你使用的是Nginx,编辑/etc/nginx/sites-available/default
文件,添加或修改以下内容:
location / {
root /var/www/html;
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$query_string;
}
sudo systemctl restart apache2
对于Nginx:
sudo systemctl restart nginx
/var/www/html
)下创建一个PHP文件(例如upload.php
),并添加以下代码:<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$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;
}
// 检查$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.";
}
}
}
?>
<!DOCTYPE html>
<html>
<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>
http://your_server_ip/upload.php
),然后尝试上传一个文件。如果一切正常,你应该能够看到文件已成功上传的消息。注意:出于安全考虑,请确保你的上传目录(在本例中为uploads/
)不允许执行PHP脚本。你可以通过在.htaccess
文件中添加以下内容来实现:
php_value engine off