【问题标题】:PHP file_get_contents(file.php); execute PHP code in filePHP file_get_contents(file.php);在文件中执行 PHP 代码
【发布时间】:2018-02-12 21:40:40
【问题描述】:

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

所以:

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

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

file.php 中的示例代码:

<?php
//simplified php code
var $item = "hello";
var $item2 = "Hola";
var $item3 = "おはよ";
?>

<section id="content">
<?php echo $item1; ?>  
</section>
<section id="content2">
<?php echo $item2; ?>
</section>
<section id="content3">
<?php echo $item3; ?>
</section>
?>

index.php 中的代码:

$content = file_get_contents('file.php');
if (isset($_GET['item'])) {
$section = $_GET['item'];
} else {
$section = 'content';
}
$delimiter = '<section id="' . $section . '">';
$start = explode($delimiter, $content);
$end = explode("</section>", $start[ 1 ] );
echo $end[0];

所以如果浏览器 url 显示 index.php?item=content2 ,它应该显示来自名为 content2 的部分 ID 的内容,以及该文件中执行的 PHP 代码。

目前,如果我这样做,什么都不会显示,并且查看源代码,显示 php 代码

【问题讨论】:

  • 我认为你需要重新设计你的方法,file_get_contents 一个本地 php 文件并部分执行它是不切实际的。让我们假设eval 应该是不可能的,将需要包含,或者为您的每个部分单独文件,或者创建一个类来包含您拥有的所有单独任务。
  • 你想在这里达到一定程度的模板化吗?
  • 这是一个模板的事情。它使用 index.php 文件中定义的相同 CSS(每个部分)。所以“部分”只是需要填写的内容。尽量减少,不想把30个项目放在30个单独的文件中。

标签: php file-get-contents


【解决方案1】:

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

ob_start();
include('file.php');
$content = ob_get_clean();

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

$content = file_get_contents('http://example.com/file.php');

【讨论】:

  • 天啊“Doh”时刻。抱歉,我忘记了 ob_start() 和 ob_get_clean(); !!谢谢,这实际上解决了它!
猜你喜欢
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
相关资源
最近更新 更多