views:

130

answers:

3

Hey guys, 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 '<'. 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'].

Thanks Matt

+4  A: 

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');
Cryo
A: 

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>";
Guffa
Why the downvote? If you don't explain what it is that you don't like, it's rather pointless.
Guffa
+3  A: 

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%}.

Karsten