开发者

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

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.


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.


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜