phpmysqlsqlob-get-contents

How to return php code from mysql record?


How to return php code from mysql row 'content' record where it might contain just plain text like:

Hello!

or/and php like:

Lets try some php: <?php echo phpinfo(); ?>

without casing speed performance when it contains just plain text?


Here is an example when it returns php on using include(), but in this case it's not what I am asking for (I am asking the case where all content php will come from mysql).

mysql record:

+---------------+
| id |  content |
|---------------|
|  0 | test.php |
+---------------+

test.php content <?php echo phpinfo(); ?>

trying to return php from mysql trough include() :

$result=mysql_query("SELECT content FROM test WHERE id=0");
while($row=@mysql_fetch_array($result,MYSQL_ASSOC)){
    $row[]=array('row'=>array_map('htmlspecialchars',$row));
    $content=$row['content'];
    ob_start();
    include $content;
    $content=ob_get_contents();
    ob_end_clean();
    echo $content;
}
mysql_close($con);

Solution

  • Try to evaluate the content of the record: eval($row['content']);

    COMPLEMENT: You have a mixed html+php code in your case and this means that you need to use a closing PHP tag to leave PHP mode, so in your particular case this may look something like this:

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

    Note: leave the extra space after the opening tag, because it has some issues: http://www.php.net/manual/en/function.eval.php#97063