在Ubuntu下处理PHP文件上传,你需要遵循以下步骤:
<!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>
这里,enctype="multipart/form-data"
属性是必须的,因为它允许表单提交二进制文件。
<?php
$target_dir = "uploads/"; // 指定上传文件的目录
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); // 获取上传文件的完整路径
$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"] . ".";
} else {
echo "File is not an image.";
}
}
// 检查文件是否已存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
} 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.";
}
}
?>
mkdir uploads
chmod 755 uploads
uploads
目录。注意:在实际应用中,你可能需要添加更多的验证和安全措施,例如检查文件类型、大小限制、防止跨站伪造请求(CSRF)等。