PHP file_get_contents(file.php); 执行文件中的PHP代码

Keo*_*oki 2 php file-get-contents

我目前遇到一个问题,我在一个文件中有一些 php 代码并从另一个文件调用该文件。

\n\n

所以:

\n\n

index.php 正在调用 file.php 并且 file.php 中有一些 php 代码。

\n\n

我使用 file_get_contents 的原因是我在 index.php 中有代码,只需要读取 file.php 中由标签指定的一些内容。基于 ($_GET[\'identifier\']) 触发的节标记;file.php 中的该部分是唯一显示的部分

\n\n

file.php 中的示例代码:

\n\n
<?php\n//simplified php code\nvar $item = "hello";\nvar $item2 = "Hola";\nvar $item3 = "\xe3\x81\x8a\xe3\x81\xaf\xe3\x82\x88";\n?>\n\n<section id="content">\n<?php echo $item1; ?>  \n</section>\n<section id="content2">\n<?php echo $item2; ?>\n</section>\n<section id="content3">\n<?php echo $item3; ?>\n</section>\n?>\n
Run Code Online (Sandbox Code Playgroud)\n\n

index.php 中的代码:

\n\n
$content = file_get_contents(\'file.php\');\nif (isset($_GET[\'item\'])) {\n$section = $_GET[\'item\'];\n} else {\n$section = \'content\';\n}\n$delimiter = \'<section id="\' . $section . \'">\';\n$start = explode($delimiter, $content);\n$end = explode("</section>", $start[ 1 ] );\necho $end[0];\n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,如果浏览器 URL 显示 index.php?item=content2 ,它应该显示名为 content2 的节 ID 中的内容,以及该文件中执行的 PHP 代码。

\n\n

目前,如果我这样做,不会显示任何内容,并且查看源代码,显示 php 代码

\n

Abr*_*ver 5

要在获取内容之前执行代码,您需要include捕获输出:

ob_start();
include('file.php');
$content = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)

或者通过 URL 获取文件(可能不是最好的主意并且不可移植):

$content = file_get_contents('http://example.com/file.php');
Run Code Online (Sandbox Code Playgroud)