php 实现文件共享
使用 PHP 实现文件共享
PHP 可以通过多种方式实现文件共享功能,以下是一种常见的实现方法,包含文件上传、下载和列表展示功能。
文件上传功能
创建一个 HTML 表单用于文件上传,PHP 接收并保存文件到指定目录。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
PHP 处理上传逻辑(upload.php):

<?php
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// 检查文件是否已存在
if (file_exists($targetFile)) {
echo "文件已存在";
$uploadOk = 0;
}
// 检查文件大小(限制为5MB)
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "文件过大";
$uploadOk = 0;
}
// 允许的文件类型
$allowedTypes = array('jpg', 'png', 'jpeg', 'gif', 'pdf', 'doc', 'docx', 'txt');
if (!in_array($fileType, $allowedTypes)) {
echo "不支持的文件类型";
$uploadOk = 0;
}
// 上传文件
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "文件上传成功";
} else {
echo "上传失败";
}
}
?>
文件列表展示
创建一个页面显示所有可下载文件(list.php):
<?php
$dir = "uploads/";
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
echo '<a href="download.php?file=' . urlencode($file) . '">' . $file . '</a><br>';
}
}
?>
文件下载功能
实现文件下载功能(download.php):

<?php
$file = $_GET['file'];
$filepath = "uploads/" . $file;
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
} else {
echo "文件不存在";
}
?>
安全注意事项
确保上传目录不可执行脚本,可通过在 uploads 目录中放置 .htaccess 文件实现:
php_flag engine off
限制文件上传类型和大小,防止恶意文件上传。定期清理上传目录,删除不必要或过期的文件。
扩展功能
可以添加用户认证系统,只有登录用户才能上传或下载文件。使用数据库记录文件信息,添加文件描述、上传者、上传时间等元数据。实现文件分类和搜索功能,提升用户体验。
替代方案
对于更复杂的文件共享需求,可以考虑使用现成的开源解决方案如 Nextcloud 或 ownCloud,它们基于 PHP 开发,提供完整的文件共享和管理功能。






