php 8.6提供小文本预览接口时,可以先把文档id映射到服务端固定文件,再限制文件类型、字节量和utf-8编码,最后用text/plain返回。客户端只传id,不传目录或文件名;预览接口也需要现有的访问权限检查。

PHP手册中的fstat
通过固定映射打开并限制读取
<?php // 此段位于已经验证当前用户文档访问权限的路由中。
$map=['guide'=>'guide.txt','changes'=>'changes.txt'];
$id=$_GET['id']??'';
if (!is_string($id) || !isset($map[$id])) { http_response_code(404); exit; }
$root=realpath('/srv/app-private/preview');
if ($root===false) throw new RuntimeException('预览目录未准备');
$file=$root.DIRECTORY_SEPARATOR.$map[$id];
if (is_link($file)) { http_response_code(404); exit; }
$real=realpath($file);
if ($real===false || !str_starts_with($real,$root.DIRECTORY_SEPARATOR)) {
http_response_code(404); exit;
}
$error=null;
$fp=fopen($real,'rb');
if ($fp===false) throw new RuntimeException('文件打开失败');
try {
$stat=fstat($fp);
if ($stat===false || ($stat['mode']&0170000)!==0100000) {
throw new RuntimeException('不是普通文件');
}
$text='';
while (!feof($fp) && strlen($text)65536) throw new LengthException();
if (str_contains($text,"\0") || preg_match('//u',$text)!==1) {
throw new UnexpectedValueException();
}
} catch (LengthException) { $error=413; }
catch (UnexpectedValueException) { $error=415; }
finally { fclose($fp); }
if ($error!==null) { http_response_code($error); exit; }
header('Content-Type: text/plain; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: private, no-store');
echo $text;

PHP手册中的fread
目录必须由受信任的部署流程维护
固定映射和realpath限制缩小了可访问范围,但打开前的路径检查不能单独消除检查与使用之间的竞争条件。预览树及其上级目录不能由不受信任用户写入或替换;需要处理攻击者可修改的目录时,应使用更强的操作系统隔离和文件打开策略。
这是小文本预览,不是任意文件下载
示例最多读取65537字节,用额外一个字节判断超限,响应上限为64KiB。它拒绝NUL和非法UTF-8,不会自动转码、解压或渲染HTML。页面若把结果放进界面,也应使用文本节点;不要再把拿到的字符串作为innerHTML执行。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










