开发者

When (if ever) would you do this in PHP?

开发者 https://www.devze.com 2023-02-20 23:01 出处:网络
I\'ve been going through the code of a Wordpress plugin and found the following: eval( \'?>\' . $foo . \'<?php \' );

I've been going through the code of a Wordpress plugin and found the following:

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

I'm curious if there is some specific situation I'm unaware of that this would be 开发者_开发技巧the right way to output the $foo variable. Is this just a case of the plugin author being wacky or is there something I should know? I would have just used echo...

UPDATE:

Thanks for all the great feedback. I'm face palming now that I didn't think of the template scenario. Specifically, this happens in the WP Super Cache plugin. I guess I'll have to have a closer look to see if it's necessary. I thought Super Cache cached the html output by Wordpress after all the PHP had already been processed...


In this instance, $foo is a string that (presumably) can contain in-lined PHP code. As such, to execute this PHP code, the string needs to be eval'ed.

That said, the use of eval is generally frowned upon, apart from in a very narrow set of circumstances, as it can lead to the execution of malicious code. (i.e.: If there's any possibility that $foo is a user-provided string, then use of eval could lead to disastrous consequences.)

See the existing When is eval evil in php? question/answers for more information.


That's not outputting the variable. $foo most likely contains a template, with other <?=$code();?> snippets embbeded.

The closing and opening PHP marker are used in this eval to switch from inline code, back to HTML mode. This eval() more or less amounts to:

include("data:,$foo");  // treat $foo string as if it was include script


Let me repeat it again: c.r.a.p

If eval() is the answer, you're almost certainly asking the wrong question.

Rasmus Lerdorf

0

精彩评论

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