tags:

views:

424

answers:

4

Hi,

I've got PHP and HTML code stored in a database table. When I get this data, I need to echo the HTML and process the PHP. I thought I could use eval() for this, which works, if I do this eval("echo 'dlsj'; ?> EVALED "); I get dlsjEVALED printed out.

The problem is, I get a fatal error when I run longer scripts. Things like: Parse error: syntax error, unexpected '<' in /home/content.php(18) : eval()'d code on line 1

Any advice = awesome.

Thanks.

+10  A: 

Best advice - never store php and html code in your database. And avoid eval() like the plague.

I can't really tell what's wrong with your code, as you haven't provided enough information. But even if I did have some advice, I don't think I could give it in good conscience.

You should redesign your whole application so that it doesn't require storing such things in the database. I can't imagine why it would be necessary.

Tesserex
A: 

I would guess that you're trying to eval() something that contains an opening <?php tag. And that leads to the error at hand.

Konrad Neuwirth
Correct, I am. But I need to, in this way:<p>text</p><?php do_php_stuff(); ?><p>more text</p>
i-CONICA
A very ugly solution for the problem at hand would be to write out the stuff form the database to a temporary file, and then load that ...This would at least achieve what you try to get.
Konrad Neuwirth
+1  A: 

You need to re-open php mode after the EVALED. Apparently you have to do this with <? rather than the full <?php.

As a rule eval is to be avoided. But rules are made to be broken. There's a thread at http://stackoverflow.com/questions/951373/when-is-eval-evil-in-php that gives some less dogmatic advice.

Depending on what you want to do, it might be suitable to use a template file that you source, with text that will vary stored in a local variable prior to sourcing the template.

As for storing code to be executed in the DB... this does happen in some frameworks like Drupal to provide convenient extensibility, but then Drupal is pretty thoroughly scoured for security weaknesses.

Also if you're writing self-modifying code then you need to use eval(). Not sure if anyone has done that in php but it would certainly be interesting.

intuited
A: 
Vishal