回声整个预编译的php页面

时间:2012-08-11 15:25:56

标签: php

例如,如果我有脚本:

<?php

     $page = "My Page";
     echo "<title>" . $page . "</title>";
     require_once('header.php');
     require_once('content.php');
     require_once('footer.php');


?>

我可以添加到该页面底部以显示整个预编译的PHP吗?

我想逐字回显php代码,而不是编译它。

所以在我的浏览器中,我会以代码形式看到以下内容......

// stuff from main php
$page = "My Page";
echo "<title>" . $page . "</title>";

// stuff from require_once('header.php');
$hello = "Welcome to my site!";
$name = "Bob";
echo "<div>" . $hello . " " . $name . "</div>";

// stuff from require_once('content.php');
echo "<div>Some kool content!!!!!</div>";

// stuff from require_once('footer.php');
$footerbox = "<div>Footer</div>";
echo $footerbox;

这可能吗?

2 个答案:

答案 0 :(得分:2)

没有办法让它本地化为PHP,但如果您只是想要一些非常简单且不健壮的东西,您可以尝试破解它:

<?php
$php = file_get_contents($_GET['file']);

$php = preg_replace_callback('#^\s*(?:require|include)(?:_once)?\((["\'])(?P<file>[^\\1]+)\\1\);\s*$#m', function($matches) {
    $contents = file_get_contents($matches['file']);
    return preg_replace('#<\?php(.+?)(?:\?>)?#s', '\\1', $contents);
}, $php);

echo '<pre>', htmlentities($php), '</pre>';

备注:

  • 警告:允许任意文件解析,就像我用第一行一样,这是一个安全漏洞。进行自己的身份验证,路径限制等。
  • 这不是递归的(尽管它不需要做太多工作),因此它不会处理其他包含文件中的包含文件等等。
  • 正则表达式匹配不健壮,而且非常简单。
  • 假定包含的文件在字符串中被静态命名。 include($foo);include(__DIR__ . '/foo.php');之类的内容无效。

免责声明:基本上,要做到这一点,您需要实际解析PHP代码。我只提供上述内容,因为这是一个有趣的问题,我很无聊。

答案 1 :(得分:1)

echo '$page = "My Page";';
echo 'echo "<title>" . $page . "</title>";';
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');

为了清楚起见,我将标题生成放在它自己的文件中,然后只使用一系列echo file_get_contents()......

echo file_get_contents('title.php');
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');