Cheesus Toast
Cheesus Toast

Reputation: 1073

Storing HTML template in an SQL database and executing it

I wish to store certain pieces of code in database tables as templates but I am unsure as to whether they are going to create problems or not. I keep reading mixed messages from various different people in different posts and I am just not happy that I am clear on this subject.

I have already worked out that you cannot really echo/ print PHP into a webpage. Obviously you can echo strings of HTML but it becomes awkward when you try to do it with PHP code. The only way I have managed to do this is through eval which is apparently bad in most cases... so I am using another method to implement the templates (i.e. writing a php file to be used as an include file)

The main question I am asking is: is there really a problem with storing the PHP code strings (which include SQL statements) inside text type fields (mediumtext, longtext etc) in tables? Could those SQL statements ever do anything like execute actual actions or would they just remain as text strings?

Just to clarify, the reason I am storing strings of code is because they are templates to be used should the web administrator wish to allocate them to a specific area (div) of the pages.

Upvotes: 0

Views: 4524

Answers (3)

nathan hayfield
nathan hayfield

Reputation: 2685

Use SMARTY or Twig template engine. This will neatly solve your problem and you will not need to store anything in the database. It will also keep your PHP code completely separate from your HTML.

Another option is to use

Upvotes: 5

gabrielkolbe
gabrielkolbe

Reputation: 145

I can see the need for code in the database for instance if you have multiple sites and want to do a source control between them, and not use any 3rd party software.. I would store in a database and then write the code on to a actual physical page, then run the php from that page...

Upvotes: 0

Kermit
Kermit

Reputation: 34063

Do not do this. If your database is ever compromised and someone injects malicious PHP, it may be executed. You should store the templates as files and call them when needed.

And you actually can echo/print PHP. You would do it using eval.

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Upvotes: -3

Related Questions