You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何读取并输出文件内容?白名单校验通过后返回文件文本实现方案

实现方法

你可以直接用PHP内置的readfile()或者file_get_contents()实现需求,前者不需要额外echo、会直接输出文件全部内容,性能更高,适合不需要对文件内容做二次处理的场景;后者可以把文件内容读到变量里,方便你做修改后再输出。
下面是修改后的完整代码示例:

<?php
$keys = array(
    "Key", "key1"
);

// 加??''处理未传key参数的场景,避免PHP抛出警告
$sub = $_GET["key"] ?? '';
if (in_array($sub, $keys, TRUE)) {
    // $_SERVER['DOCUMENT_ROOT']对应你public html目录的绝对路径,后面拼接文件的相对路径即可
    $target_file = $_SERVER['DOCUMENT_ROOT'] . '/替换为你的实际文件名';

    // 可选配置响应头,根据你的文件类型调整:
    // 如果是二进制可执行文件,加这行指定内容类型,避免浏览器当成普通文本解析
    header('Content-Type: application/octet-stream');
    // 如果需要让客户端触发下载,加这行,filename替换为你想展示的默认文件名
    // header('Content-Disposition: attachment; filename="client_exec.exe"');

    // 校验文件存在且可读,避免报错暴露服务器信息
    if (file_exists($target_file) && is_readable($target_file)) {
        // 方法1:直接输出文件内容,性能最优
        readfile($target_file);
    } else {
        http_response_code(500);
        echo "Server internal error";
    }

    /* 方法2:需要先处理文件内容再输出时用这个
    if (file_exists($target_file) && is_readable($target_file)) {
        $file_content = file_get_contents($target_file);
        // 这里可以加自定义的内容处理逻辑
        echo $file_content;
    } else {
        http_response_code(500);
        echo "Server internal error";
    }
    */
} else {
    echo "Not Whitelisted";
}
?>

注意事项

  • 把代码里的/替换为你的实际文件名改成你放在public html下的文件路径即可,比如文件在public html的bin目录下叫client.exe,就写成/bin/client.exe
  • 请确保目标文件的权限配置正确,允许web服务进程读取
  • 你的场景下是固定读取指定文件,没有用用户传入的参数拼接文件名,不存在路径遍历、任意文件读取的安全漏洞,可以正常使用

内容的提问来源于stack exchange,提问作者Vixillity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:06:07