How to return php code from mysql record?

How to return php code from the string "content" to mysql, where it can contain only plain text:

Hello!

or / and php, for example:

Lets try some php: <?php echo phpinfo(); ?>

without flow speed when it contains only plain text?


Here is an example when it returns php when using include (), but in this case it is not what I ask (I ask the case when all php resources will come from mysql).

mysql record:

 +---------------+ | id | content | |---------------| | 0 | test.php | +---------------+ 

test.php content <?php echo phpinfo(); ?> <?php echo phpinfo(); ?>

trying to return php from mysql trough include ():

 $result=mysql_query("SELECT content FROM test WHERE id=0"); while( $row=@mysql _fetch_array($result,MYSQL_ASSOC)){ $row[]=array('row'=>array_map('htmlspecialchars',$row)); $content=$row['content']; ob_start(); include $content; $content=ob_get_contents(); ob_end_clean(); echo $content; } mysql_close($con); 
+4
source share
2 answers

Try evaluating the contents of the entry: eval($row['content']);

COMPLEMENT: in your case, there is mixed html + php code, and this means that you need to use the closing PHP tag to exit PHP mode, so in your specific case it might look something like this:

 eval( '?>'. $row['content'] .'<?php ' ); 

Note: leave extra space after the opening tag, because it has some problems: http://www.php.net/manual/en/function.eval.php#97063

+4
source

The PHP code in DB sucks, but I was in situations where it should have been done, because my employer did not allow me to rewrite the system in such a way as to avoid it, so here is the general version of the solution we used:

 $string = 'this <?php echo "is not"; ?> cool'; function exec_php($php_string) { return preg_replace_callback( '/<\?(?:php)?(.*)\?>/m', 'exec_php_embed', $string ); } function exec_php_embed(array $args) { if (count($args) != 2) { return ''; } list(,$code) = $args; ob_start(); eval($code); return ob_get_clean(); } 

Note: VERY VERY CAUTION WITH THIS! DO NOT PERFORM THE USER'S CONTENT WITH THIS! Try replacing it as soon as possible!

Using eval() not just inefficient, it is dangerous when used even in a slightly improper way. Despite the fact that I really do not recommend using such things as it was above, I believe that this will be the solution to your immediate problem. I can not guarantee that he will not create more of his own problems;)

As GNU says:

 This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
+1
source

All Articles