根据用户输入访问文件
为什么危险
../ 之类的序列能让请求跳出预期目录,读取配置文件、密钥或源代码。
readfile('/var/files/' . $_GET['file']);
$base = realpath('/var/files');
$path = realpath($base . '/' . basename($_GET['file'] ?? ''));
if ($path === false || !str_starts_with($path, $base . '/')) {
http_response_code(404);
exit;
}
readfile($path);
修复方法
使用 basename() 和固定目录,再用 realpath() 确认文件位于目录内。
扫描我的代码
扫描我的代码 →
粘贴文件,PHP Safe 会指出所有符合此规则的代码行。