Search code examples
phphtmlsyntaxevaloutput-buffering

PHP: using the eval function with HTML and PHP code


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'].


Solution

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