开发者

PHP: using the eval function with HTML and PHP code

开发者 https://www.devze.com 2022-12-16 20:48 出处:网络
I currently have the following code coming from a database table: <h1 class=\"widgetHeader\">My Friends</h1>

I currently have the following code coming from a database table:

<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>

Now, ive tried using the eval function in php but i get a parse error unexpected '&开发者_运维百科lt;'. I've also tried using the output buffer method (ob_start) without success too. Any ideas as to how i can get this code to evaluate without giving me an error?

note: the database code is stored in a variable called $row['code'].


The PHP eval function expects PHP code to execute as it's parameter, not HTML. Try enclosing your DB values with PHP close and open tags:

eval('?>' . $row['code'] . '<?php');


eval = evil!

Especially if the eval'd code comes from a db... one mysql injection = full php execution = full control.

Rather use some placeholders and replace them (like any other good templating system does).

You could store this in your database:

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

Then str_replace the placeholders with the content they should have. In your example i would also add a subtemplate per friend like this:

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

... which you could loop and insert into {%friendstemplate%}.


You cant use eval on markup code. Either save the code to a temporary file so that you can include it, or rewrite the code so that it's not markup, something like:

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>";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号