简体   繁体   中英

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(); ?> <?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);

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

PHP Code in the DB sucks, but I've been in situations before where it had to be done because my employer would not let me rewrite the system in such a way as to avoid it, so here's a general version of the solution we used:

$string = 'this <?php echo "is not"; ?> cool';

function exec_php($php_string) {
    return preg_replace_callback(
        '/<\?(?:php)?(.*)\?>/m',
        'exec_php_embed',
        $string
    );
}

function exec_php_embed(array $args) {
    if (count($args) != 2) {
        return '';
    }
    list(,$code) = $args;
    ob_start();
    eval($code);
    return ob_get_clean();
}

Note: BE VERY VERY CAREFUL WITH THIS! DO NOT EXECUTE USER GENERATED CONTENT WITH THIS! Try to replace this as soon as possible!

Using eval() is not just inefficient, it's dangerous when used even slightly improperly. While I highly discourage the use of things like the above, I do imagine it will prove to be a solution to your immediate problem. I do not guarantee it won't create more problems of its own;)

As GNU says:

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM