PHP中的文件系统操作与安全实践
目录浏览功能实现
在PHP中可通过内置函数遍历指定目录内容,类似操作系统中的 ls 命令。常用方法包括 opendir() 与 scandir()。
使用 readdir() 遍历目录:
<?php
$dir_handle = opendir('../');
while (($entry = readdir($dir_handle)) !== false) {
echo htmlspecialchars($entry) . '<br>';
}
closedir($dir_handle);
?>
使用 scandir() 简化读取:
<?php
$entries = scandir('../');
foreach ($entries as $item) {
echo htmlspecialchars($item) . '<br>';
}
?>
文件内容读取方式对比
PHP提供了多种读取文件内容的函数,适用于不同场景。
逐字符/行读取(低内存占用):
<?php
$file_handle = fopen('data.txt', 'r');
if ($file_handle) {
while (($line = fgets($file_handle)) !== false) {
echo htmlspecialchars($line) . '<br>';
}
fclose($file_handle);
}
?>
一次性读取全文(便捷高效):
<?php
$content = file_get_contents('data.txt');
echo htmlspecialchars($content);
// 或按行分割为数组
$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
echo htmlspecialchars($line) . '<br>';
}
?>
文件下载实现
通过设置HTTP响应头可实现文件强制下载。
<?php
$target_file = './report.pdf';
if (file_exists($target_file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($target_file) . '"');
header('Content-Length: ' . filesize($target_file));
readfile($target_file);
exit;
} else {
http_response_code(404);
echo '文件不存在';
}
?>
删除文件操作
使用 unlink() 可删除指定路径文件,需注意权限控制。
<?php
$to_delete = './temp.log';
if (unlink($to_delete)) {
echo '文件已移除';
} else {
echo '删除失败:权限不足或文件不存在';
}
?>
文件包含机制详解
PHP支持将外部文件内容插入当前脚本执行,提升代码复用性。
基本包含函数差异:
include():包含失败仅警告,继续执行require():包含失败则中断程序include_once()/require_once():避免重复包含
特殊行为:文本文件可执行代码
若被包含的 .txt 文件中包含 <?php ... ?> 代码,该代码将在运行时被执行。
// test.txt 内容示例:
// <?php echo 'Hello from text file!'; ?>
// <html><body><h1>Welcome</h1></body></html>
潜在安全风险警示
当文件操作函数接收用户输入参数时,极易引发以下漏洞:
- 任意文件读取(如通过路径遍历)
- 敏感文件泄露(如配置文件、日志)
- 文件删除或覆盖攻击
- 远程代码包含(RCE)
核心原则:
任何来自用户输入的路径参数都必须经过严格验证与过滤,禁止直接拼接至文件操作函数中。