Tutorial :how to eval() a segment of a string



Question:

I have a string that has HTML & PHP in it, when I pull the string from the database, it is echo'd to screen, but the PHP code doesn't display. The string looks like this:

   $string = 'Hello <?php echo 'World';?>';     echo $string;  

Output

   Hello  

Source Code

   Hello <?php echo 'World';?>  

When I look in the source code, I can see the php line there. So what I need to do is eval() just the php segment that is in the string.

One thing to consider is that the PHP could be located anywhere in the string at any given time.

* Just to clarify, my PHP config is correct, this is a case of some PHP being dumped from the database and not rendering, because I am echo'ing a variable with the PHP code in it, it fails to run. *

Thanks again for any help I may receive.


Solution:1

$str = "Hello  <?php echo 'World';?>";    $matches = array();    preg_match('/<\?php (.+) \?>/x', $str, $matches);    eval($matches[1]);  

This will work, but like others have and will suggest, this is a terrible idea. Your application architecture should never revolve around storing code in the database.

Most simply, if you have pages that always need to display strings, store those strings in the database, not code to produce them. Real world data is more complicated than this, but must always be properly modelled in the database.

Edit: Would need adapting with preg_replace_callback to remove the source/interpolate correctly.


Solution:2

You shouldn't eval the php code, just run it. It's need to be php interpreter installed, and apache+php properly configured. Then this .php file should output Hello World.

Answer to the edit: Use preg_replace_callback to get the php part, eval it, replace the input to the output, then echo it. But. If you should eval things come from database, i'm almost sure, it's a design error.


Solution:3

eval() should work fine, as long as the code is proper PHP and ends with a semicolon. How about you strip off the php tag first, then eval it.

The following example was tested and works:

<?php  $db_result = "<?php echo 'World';?>";  $stripped_code = str_replace('?>', '', str_replace('<?php', '', $db_result));  eval($stripped_code);  ?>  

Just make sure that whatever you retrieve from the db has been properly sanitized first, since you're essentially allowing anyone who can get content into the db, to execute code.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »