【问题标题】:How to echo the source code of multiple files using file_get_contents PHP?如何使用 file_get_contents PHP 回显多个文件的源代码?
【发布时间】:2015-04-01 19:11:56
【问题描述】:
<textarea placeholder="Source code of file" class="source">
<?php echo ($thesource) ?>
</textarea>

    <?php 
       $blacklist = array("one.jps", "two.txt", "four.html");

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != ".." &&  !in_array($entry, $blacklist)) { 
$thesource = file_get_contents($entry);
            echo "<div class='post'
<p>$entry</p>
</div>
";
        }

    }

    closedir($handle);
}
    ?>

输出:

<textarea placeholder="Source code of file" class="source">
<!DOCTYPE html>
<html>
etc
etc
</body>
</html>
</textarea>

<p>ok.html</p> 
<p>source.php</p>
<p>sub.html</p>
<p>stylesheet.css</p>

这可能看起来令人困惑,让我试着解释一下我想要实现的目标。

假设目录中有一些文件(在本例中为 4 个)。我正在使用的 PHP 代码会将所有这 4 个文件回显到 PHP 代码所在的页面上 - 它排除了黑名单中的所有内容。所以它看起来有点像这样:

<p>ok.html</p> 
<p>source.php</p>
<p>sub.html</p>
<p>stylesheet.css</p>

还有一个textarea:

<textarea placeholder="Source code of file" class="source">
<?php echo ($thesource) ?>
</textarea>

此文本区域的值为 $thesource。 $thesource 变量中的任何内容都会出现在文本区域中。

要定义 $thesource 变量,这是我正在使用的 PHP 代码:

$thesource = file_get_contents($entry);

请注意,$entry 是在页面上回显的所有文件(如上所述 - 在本例中为 4 个文件)

我正在努力做到这一点,每当用户点击其中一个文件时:

<p>ok.html</p> 
<p>source.php</p>
<p>sub.html</p>
<p>stylesheet.css</p>

当用户点击上面列出的那些时,它会在文本区域中显示被点击文件的源代码。

我当前使用的源代码,只是echo's出当前包含PHP代码的文件的源代码。

我将如何实现这一目标?谢谢 - 如果您仍然不确定我想要达到的目标,请询问!

【问题讨论】:

  • 所以你想执行 php 脚本并回显生成的 html 代码?
  • 所以你想要一个特定目录中不在黑名单上的所有文件的列表,如果你点击一个文件应该显示在文本区域中?
  • 源代码是PHP?还是 HTML?
  • @Rizier123 是的,这正是我想要做的,点击其中一个文件会在 textarea 中显示该文件的源代码
  • @Osman 你还想要源代码还是解析后的php?

标签: php html directory echo file-get-contents


【解决方案1】:

这应该适合你:

首先,我将所有不在黑名单中的文件放在带有glob() 的目录中。之后我打印一个列表,你可以点击它。

如果您单击它,文件将被包含并显示在文本区域中。

<?php

    $blacklist = array("one.jps", "two.txt", "four.html");
    $files = array_diff(glob("*.*"), $blacklist);

    foreach($files as $file)
        echo "<div class='post'><a href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'><p>" . $file . "</p></a></div>";


    if(!empty($_GET["file"]) && !in_array($_GET["file"], $blacklist) && file_exists($_GET["file"])) 
        $thesource = htmlentities(file_get_contents($_GET["file"]));

?>

<textarea rows="40" cols="100" placeholder="Source code of file" class="source"><?php if(!empty($thesource))echo $thesource; ?></textarea>

【讨论】:

  • 感谢您的帮助,但有没有办法在不必访问新页面的情况下执行此操作?一旦用户点击文件,脚本就会工作,但是他会被发送到一个新的 URL。有没有办法从一页做这一切?
  • 感谢您的帮助,但作为跟进,是否可以在不将 URL 更改为 example.com/test?file=one.html 的情况下执行此操作,因为这是一个主要的安全漏洞,因为用户可以直接更改“one.html”到他们想要的任何文件(即,一个 PHP 文件并访问 PHP 代码),再次感谢
  • @Osman 您可以使用会话变量将文件名保存在其中
  • @Osman 我不太会用 AJAX,所以我帮不了你
猜你喜欢
  • 2014-09-14
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
相关资源
最近更新 更多