0

我目前有来自数据库表的以下代码:

<h1 class="widgetHeader">My Friends</h1>
<div class="widgetRepeater">            
    <p class="widgetHeader">Random Selection</p>
<?php 
    $friends = $user->getFriends(); 
?>
    <p class="widgetContent">
<?php 
        for ($i=0; $i<count($friends);$i++) { 
            $friend = $friends[$i]; 
?>
                <span class="friendImage" style="text-align:center;">
                    <?php print $friend->username; ?>
                </span> 
<?php 
        }
?>      
    </p>

</div>

现在,我尝试在 php 中使用 eval 函数,但我得到一个意外的解析错误'<'。我也尝试过使用输出缓冲区方法(ob_start)也没有成功。关于如何在不给我错误的情况下评估此代码的任何想法?

注意:数据库代码存储在一个名为$row['code'].

4

3 回答 3

4

PHP eval 函数期望 PHP 代码作为参数执行,而不是 HTML。尝试使用 PHP 关闭和打开标签封闭您的数据库值:

eval('?>' . $row['code'] . '<?php');
于 2010-01-17T11:53:09.187 回答
3

评价=邪恶!

特别是如果 eval 代码来自 db... 一个 mysql 注入 = 完全 php 执行 = 完全控制。

而是使用一些占位符并替换它们(就像任何其他好的模板系统一样)。

您可以将其存储在数据库中:

<h1 class="widgetHeader">My Friends</h1>
<div class="widgetRepeater">            
    <p class="widgetHeader">Random Selection</p>
    {%friendstemplate%}
</div>

然后将 str_replace 占位符替换为应有的内容。在您的示例中,我还将为每个朋友添加一个子模板,如下所示:

<span class="friendImage" style="text-align:center;">
    {%username%}
</span>

...您可以循环并插入到 {%friendstemplate%}。

于 2010-01-17T12:37:53.420 回答
0

您不能eval在标记代码上使用。将代码保存到临时文件以便您可以包含它,或者重写代码使其不是标记,例如:

print "<h1 class=\"widgetHeader\">My Friends</h1>";
print "<div class=\"widgetRepeater\">";
print "<p class=\"widgetHeader\">Random Selection</p>";
$friends = $user->getFriends(); 
print "<p class=\"widgetContent\">";
for ($i=0; $i<count($friends);$i++) { 
   $friend = $friends[$i];
   print "<span class=\"friendImage\" style=\"text-align:center;\">";
   print $friend->username;
   print "</span>";
}
print "</p>";
print "</div>";
于 2010-01-17T11:57:07.320 回答