在Ubuntu下使用PHP实现文件上传,可以按照以下步骤进行操作:
首先,创建一个HTML表单,允许用户选择要上传的文件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
接下来,创建一个PHP脚本来处理文件上传。将这个脚本命名为upload.php
。
<?php
// 检查是否有文件被上传
if (isset($_FILES['fileToUpload'])) {
$target_file = "uploads/" . 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.";
}
}
}
?>
确保在项目根目录下创建一个名为uploads
的目录,并设置适当的权限,以便PHP脚本可以将文件写入该目录。
mkdir uploads
chmod 755 uploads
确保你的PHP配置允许文件上传。编辑php.ini
文件(通常位于/etc/php/7.x/apache2/php.ini
或/etc/php/7.x/cli/php.ini
),并检查以下设置:
file_uploads = On
upload_max_filesize = 50M
post_max_size = 50M
根据需要调整upload_max_filesize
和post_max_size
的值。
将HTML文件和PHP脚本放在你的Web服务器的根目录下(例如/var/www/html
),然后通过浏览器访问HTML文件,尝试上传文件。
通过以上步骤,你应该能够在Ubuntu下使用PHP实现文件上传功能。