【问题标题】:Include code from a PHP stream包含 PHP 流中的代码
【发布时间】:2011-05-22 07:42:29
【问题描述】:

我想知道是否有可能创建一个流包装器,以便将一些代码从数组加载到使用类似以下的东西中

<?php include 'template://myarraykey/'; ?>

它是否像从文件中执行普通包含一样工作?问的原因是因为我真的不想将模板存储在文件系统上,它们要么存在于 memcache 中,要么存在于数据库表中,并且绝对不想使用 eval()。

我还假设我需要将 allow_url_include 设置为 on?

【问题讨论】:

    标签: php include stream


    【解决方案1】:

    我知道这是一个老问题...但我认为值得注意的是,您可以执行以下操作:

    $content = '
      <?php if($var=true): ?>
        print this html
      <?php endif; ?>
    ';
    

    通常这会很麻烦,但你可以这样做:

    include "data://text/plain;base64,".base64_encode($content);
    

    它会像解析它一样快速!

    【讨论】:

    • 这仅在启用 allow_url_include 时有效。
    【解决方案2】:

    Include 可以采用任意 url。阅读this。这是从那里获取的示例 HTTP 代码:

    <?php
    
    /* This example assumes that www.example.com is configured to parse .php
    * files and not .txt files. Also, 'Works' here means that the variables
    * $foo and $bar are available within the included file. */
    
    // Won't work; file.txt wasn't handled by www.example.com as PHP
    include 'http://www.example.com/file.txt?foo=1&bar=2';
    
    // Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
    // local filesystem.
    include 'file.php?foo=1&bar=2';
    
    // Works.
    include 'http://www.example.com/file.php?foo=1&bar=2';
    
    $foo = 1;
    $bar = 2;
    include 'file.txt';  // Works.
    include 'file.php';  // Works.
    
    ?>
    

    只需将其更改为include "template://$thevalue";

    【讨论】:

    • 经过一些编码和一些测试后,我得出的结论是,我在吠叫错误的树,因为在这种情况下使用流与 evil() 有相同的问题,我改为决定将其存储在数据库中并缓存到文件系统中,这样它就可以从 APC 缓存中受益,并且在每次模板编辑后我都会更新文件系统缓存。
    【解决方案3】:

    eval 这个词并不邪恶。你可以用它做的事情是。任何做你想做的事的方法都会有与 eval 相同的风险。所以只需使用 eval,因为保护它是一个更“已知”的问题。

    【讨论】:

      【解决方案4】:

      由于include 可以使用任何适当的流,并且您可以注册自己的流包装器,我不明白为什么不这样做。

      为了好玩,您可以尝试另一种选择:从 memcached 加载数据并使用 data stream wrapper 包含它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-17
        • 2015-08-21
        • 1970-01-01
        • 2014-05-19
        • 1970-01-01
        相关资源
        最近更新 更多