PHP eval() code in between <?php ?> from database

笑着哭i 提交于 2019-11-30 16:30:54

问题


I want to be able to put PHP into the database and run it. I have to do this because I store page layouts in the database and each our different for each other, however in some cases I want to use dynamic content for some of the pages.

Assume $query_from_db is the string returned from the database. PHP should only eval() the code in between <?php and ?>

$query_from_db  = '<div>
<?php

//php to run
function dosomething() {
     //bleh
}

?>
</div>
';


php echo eval($query_from_db);

How can I do this? I'm aware this is not recommended.


回答1:


I'm not arguing about the sense or nonsense of this approach. To some extend, this is a valid question.

See the documentation:

To mix HTML output and PHP code you can use a closing PHP tag to leave PHP mode.

So you have to do:

eval('?> ' .  $query_from_db . ' <?php ');

DEMO

Also note that eval is outputting directly to the browser. It does not return a value. Have a look at Output Control Functions for buffering.




回答2:


You are aware that this is not recommended and I strongly urge everyone to review the comments to this question.

But to provide an answer:

<?php

$string = 'hello <?php echo "world"; ?>';

eval('?>'.$string.'<?'); // will output "hello world";

be aware that this however will not work:

<?php

$string = 'hello <?php echo "world"; ?>';

eval('?>'.$string.'<?php'); // error will be thown

This works again:

<?php

$string = 'hello <?php echo "world"; ?>';

eval('?> '.$string.' <?php '); // will output "hello world";

i am not really sure why.

following up on your comment to grab the output you can do:

<?php

$string = 'hello <?php echo "world"; ?>';

ob_start();
eval('?> '.$string.' <?php '); // will output "hello world";
$output = ob_get_clean(); // $output will now contain "hello world". No text will have ben printed.



回答3:


If you want to avoid the eval stigmata, you can alternatively use:

include("data:,$query_from_db");

It's just another name for eval which doesn't upset people as much. It depends on the php.ini setting allow_url_include however.

What you are doing is functionally equivalent to include("$template/$by_name.php"); and just differs in that you didn't put the database content into a file before. (But that's the other workaround: file_put_contents && include).



来源:https://stackoverflow.com/questions/5072434/php-eval-code-in-between-php-from-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!