Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 765
Endophage Avatar asked Mar 31 '11 20:03

Endophage


2 Answers

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.

like image 120
John Parker Avatar answered Oct 08 '22 10:10

John Parker


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
like image 32
mario Avatar answered Oct 08 '22 09:10

mario