Forum Moderators: coopster
I am trying to find an appropiate method by which I can store php code in a database, and then parse the code when it is retrieved from the database using PHP.
Eval seems to be the way to go (open to suggestions on this), but I am just trying to get a simple example working. What is stumping me at the moment is being able to include the declaration of PHP variables in the string stored in the database. Escaping the $ in front of the variable declarations was suggested in some eval tutorials but to no avail.
Here is my test code
$php = "<? \$1 = \"abc\"; ?>this is the text with php code in it. <? echo \$1; ?>";
ob_start();
eval(" ?>" . $php . "<? ");
$output = ob_get_contents();
ob_end_clean();
echo $output;
and this is the error I am receiving
Parse error: syntax error, unexpected T_LNUMBER, expecting T_VARIABLE or '$' in /blah/web09/b1130/xyz.blah/htdocs/eval-test.php(31) : eval()'d code on line 1
If I change the value of the $php variable to
$php = "This is the text with php code in it. <? echo date('H:M:S'); ?>";
The PHP parses fine.
If anybody can shed some light on this I would be really grateful. Alternatively if you can think of a more suitable method for getting PHP out of a database and then parsed please shout up!
$php = '<? $1 = "abc"; ?>this is the text with php code in it. <? echo $1; ?>'; Possibly the problem you're having is a result of your eval line:
eval(" ?>" . $php . "<? "); This is ultimately creating something like this:
?><? $1 = "abc"; ?>this is the text with php code in it. <? echo $1; ?><? Try just eval($php) instead.
Parse error: syntax error, unexpected '<' in /blah/web09/b1130/xyz.blah/htdocs/eval-test.php(32) : eval()'d code on line 1
I can't remove the opening <? as it won't parse so that leaves me a bit stumped. Any further ideas very welcome!
First, $1 is reserved, second, when you run the eval you're already in PHP mode so there's no need for the opener.
This should work:
$php = '$test = "abc"; ?>this is the text with php code in it. <? echo $test;';
ob_start();
eval($php);
$output = ob_get_contents();
ob_end_clean();
echo $output;
exit();
I didn't know that $1 was a reserved variable so off to read up on that.
Thanks for your help IanK - very much appreciated!
[edited by: Sagaris at 12:02 pm (utc) on April 22, 2008]