Storing HTML template in an SQL database and executing it - php

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.

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

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...

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.

Related

How to store user content while avoiding XSS vulnerabilities

I know similar questions have been asked but I am struggling to work out how to do it.
I am building a CMS, rather primitive right now, but it's as a learning exercise; in a production site, I would use an existing solution for sure.
I would like to take user input, which can be styled in a WYSIWYG editor. I would also like them to be able to insert images inline.
I understand I can store HTML in the database but how can I safely re-render this. I know there is no problem with the HTML being stored but it is my understanding that XSS become an issue if I were to just simply dump the user-generated code onto a layout template.
So the question put simply, is how can I store and safely rerender user content in cms? I am using Laravel and PHP. I also have a little knowledge of javascript if its required.
For a CMS where you want to allow some tags but not others, then you want something like HTML Purifier. This will take HTML and run it against a whitelist and regenerate HTML that is safe to display back to the user.
A good and cheap way to avoid cross-site scripting is to get your php program to entitize everything from your users' input before storing it in the database. That is, you want to take this entry from a user
Hi there sucker! I just hacked your site.
<script>alert('You have been pwned!')</script>
and convert it to this before putting it into your database.
Hi there sucker! I just hacked your site.
<script>alert('You have been pwned!')</script>
When you pass < to a browser, it renders it as <, but it doesn't do anything else with it.
The htmlentities() function can do this for you. And, php's htmlspecialchars_decode() can reverse it if you need to. But you shouldn't reverse the operation unless you absolutely must do so, for example to load the document into an embedded editor for changes.
You can also choose to entitize user-furnished text after you retrieve it from your database and before you display it. If you get to the point where several people work on your code, you may want to do both for safety.
You can also render user-provided input inside <pre>content</pre> tags, which tells the brower to just render the text and do nothing else with it.
(Use right-click Inspect on this very page to see how Stack Overflow handles my malicious example.)

Is it possible to execute PHP code returned from a MySQL query result?

The issue I am having is as follows: I have a MySQL table that contains details for page content I wish to display on my site. The content for one of my pages however I wanted to contain some actual PHP code to be executed, not just printed as a string. For example:
require_once("Class.php");
Class::Function("Some Text For a Parameter");
I want this code to execute somehow when the sql query is returned but as it stands, it just prints that text out. Is there a way to achieve what I want?
Thankyou in advance for your time,
Regards,
Stephen.
You can do it with eval(), but you shouldn't.
they are several ways to achieve the storage of dynamic elements :
eval(str) : you can evaluate as php code any string coming from you database. This is not very wise if what is stored in the database comes directly from a user input field. You never know what is going to be inserted and it could potentially be harmful code (harmful to the security of your server)
save / include : you could save what comes from your database in a temporary file and include() that file in-place in your php code. This does not seem to be secure either if anyone can store anything in your database
use a templating engine that has a reasonnable command footprint like smarty or mustache. you can store the templates in your database and execute them. If you trust the implementation of the templating language (and disable native php calls inside smarty for example) the template will need to have a correct syntax before execution can begin
As a general rule of thumb, it is very hard to protect such dynamic php code inclusion, so it should be considered as bad practice.
You should consider a DSL (domain specific language) for which you will trust the parser/compiler and execution engine.
If security is not a concern (because your application will not be public for example) then it can be perfectly valid and effective to store php fragments in the database.
I hope this will help you
Jerome Wagner
I do a variation of this in my personal CMS by doing a bbcode of sorts. I enclose php to evaluate inside of [code][/code] tags, then when displaying I have a function that uses regular expressions to grab the contents of code inside the [code] tags to run. It in turn builds the code such that it closes the text echo, runs the script, then starts the text echo again. Perhaps the explanation is a bit simplistic, but you get the idea.
I would definitely avoid eval!

Best way to create a "template interpreter" in PHP

I'm hosting a multi area solution written in PHP, and each customer has its own template in some HTML files. Now I want these users to be able to use some chunks of dynamic content, but they can't be able to use PHP. I thought something like:
In the HTML file, if I put this:
<ul>[menu-list]</ul>
Will output something like:
<ul><li><a[...]>Home</a></li><li><a[...]>About</a></li>[...]</ul>
Is there any better way of doing it than keep parsing and caching files via file_get_contents() and preg_match_all()?
I want to create about 20 entries like [menu-list], and parsing every file for all of them seems quite expensive to me.
I'd appreciate any suggestion. =D
Perhaps you should consider using a template compiler instead of a template interpreter. That is, instead of each time the page is loaded doing this whole replacement procedure you could simply perform the replacement after the template has been modified. During template editing the cost should be negligible. To implement this compilation you could choose to "compile" in some breadcrumbs so you can go backwards, or you can simply save the original template files for later editing.
Alternatively, you could consider using PHP variable naming conventions and running your templates through an eval, but this poses a number of other issues (like security threats) and doesn't come highly recommended.
Why can't you use Smarty and friends? I would not want to write what you suggest myself.

How should I store textual data that won't change very often?

As an exercise in web design and development, I am building my website from the ground up, using PHP, MySQL, JavaScript and no frameworks. So far, I've been following a model-view-controller design. However, there is one hurdle that I am quickly approaching that I'm not sure how I'm going to solve, but I'm sure it's been addressed before with varying degrees of success.
On my website, I'm going to have a resume and an "about me" bio section. These probably won't be changing very often.
For my resume, I think that XML that can be rendered into HTML (or any other format) is the best option, and in that case, I could even build a "resume manager" using PHP that can edit the underlying XML. A resume also seems like it could be built on top of MySQL, as well, and generated into XML or HTML or whatever output format I choose.
However, I'm not sure how to store my about me/bio. My initial idea was a plain text document that can be read it, parsed, and the line breaks converted to paragraphs. However, I'm not sold on that being the best idea. My other idea was using MySQL, but I think that might be overkill for a single page. What I do know, however
What techniques have you used when storing text for a page that will not change very often? How did they work out for you - what problems or successes did you have?
Like McWafflestix said, use HTML, if you want to output HTML. Simplest case within PHP:
<?php
create_header_stuff();
include('static_about.html');
create_footer_stuff();
?>
and in static_about.html something like
<div id="about">
...
</div>
Cheers,
Just use a static page, if the information won't change very often. Just using static HTML gives you more control over the display format.
Generally treating infrequently changing information the same as frequently changing information works well if you add one other component: caching.
Whatever solution you decide on for the back end, store the output in a cache and then check to see if the data has changed. Version numbers or modified dates work well here. If it hasn't changed, just give the cached data. If it has changed then you rebuild the content, cache it and display.
As far as structure goes, I tend to use text blobs in a database if there is any risk that there will be more dynamic databases. XML is a great protocol for communicating between services and as an intermediate step, but I tend to use a database under all my projects because eventually I end up using it for other things anyway.

separating php and html... why?

So I have seen some comments on various web sites, pages, and questions I have asked about separating php and html.
I assume this means doing this:
<?php
myPhpStuff();
?>
<html>
<?php
morePhpStuff();
?>
Rather than:
<?php
doPhpStuff();
echo '<html>';
?>
But why does this matter? Is it really important to do or is it a preference?
Also it seems like when I started using PHP doing something like breaking out of PHP in a while loop would cause errors. Perhaps this is not true anymore or never was.
I made a small example with this concept but to me it seems so messy:
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
?>
<b>Fatty has </b><?php echo $cookies; ?> <b>cookies left.</b><br>
<?php
}
?>
Are there instances when it is just better to have the HTML inside the PHP?
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
echo'<b>Fatty has </b> '.$cookies.' <b>cookies left.</b><br>';
}
?>
When people talk about separating PHP and HTML they are probably referring to the practice of separating a website's presentation from the code that is used to generate it.
For example, say you had a DVD rental website and on the homepage you showed a list of available DVDs. You need to do several things: get DVD data from a database, extract and/or format that data and maybe mix some data from several tables. format it for output, combine the DVD data with HTML to create the webpage the user is going to see in their browser.
It is good practice to separate the HTML generation from the rest of the code, this means you can easily change your HTML output (presentation) without having to change the business logic (the reading and manipulation of data). And the opposite is true, you can change your logic, or even your database, without having to change your HTML.
A common pattern for this is called MVC (model view controller).
You might also want to look at the Smarty library - it's a widely used PHP library for separating presentation and logic.
Let's make it clear what is not separation
you switch from php mode to html mode
you use print or echo statements to write out html code
you use small php snipplets inside html files
If you do this, there is no separation at all, no matter if you escape from php to html blocks or do it the other way and put php code into html.
Have a look at a good templating engine, there are a plenty of reasons in the "why use ...." parts of the manuals. I'd suggert www.smarty.net especially http://www.smarty.net/whyuse.php
It will answer all your questions now you have.
It is very important to separate application logic from presentation logic in projects. The benefits include:
Readability: Your code will be much easier to read if it does not mix PHP and HTML. Also, HTML can become difficult to read if its stored and escaped in PHP strings.
Reusability: If you hard-code HTML strings within PHP code, the code will be very specifc to your project and it won't be possible to reuse your code in later projects. On the other hand, if you write small functions that do one task at a time, and put HTML into separate template files, reusing your code in future projects will be possible and much easier.
Working in a team: If you are working in a team that contains developers and designers, separation of application logic and presentation templates will be advantageous to both. Developers will be able to work on the application without worrying about the presentation, and designers (who don't necessarily know PHP very will) will be able to create and update templates without messing with PHP code.
for pages that contain a lot of HTML, embedding PHP code into the page could be easier. this is one of the first intentions behind PHP. anyway when you are developing an application with lots and lots of logic, different types of connectivity, data manipulation, ... your PHP code gets too complicated if you want to just embed them in the same pages that are shown to users. and then the story of maintenance begins. how are you going to change something in the code, fix a bug, add a new feature?
the best way is to separate your logic (where most of the code is PHP) in different files (even directories) from your page files (where most of the code is HTML, XML, CSV, ...).
this has been a concern for developers for so many years and there are recommendations to handle these general problems, that are called design patterns.
since not everyone has the experience, and can apply these design patterns into his application, some experienced developers create Frameworks, that will help other developers to use all the knowledge and experience laying in the hear of that framework.
when you look at toady's most used PHP frameworks, you see that all of them put code into PHP Classes in special directories, make configurations, and .... in none of these files you see a line of HTML. but there are special files that are used to show the results to users, and they have a lot of HTML, so you can embed your PHP values inside those HTML pages to show to users. but remember that these values are not calculated on the same page, they are results of a lot of other PHP codes, written in other PHP files that have no HTML in them.
I find it preferable to separate application logic from the view file (done well with CodeIgniter framework with MVC) as it leaves code looking relatively tidy and understandable. I have also found that separating the two leaves less margin for PHP errors, if the HTML elements are separated from the PHP there is a smaller amount of PHP that can go wrong.
Ultimately I believe it is down to preference however I feel that separation has the following pros:
Tidier Code
Less of an Error Margin
Easy to Interpret
Easier to change HTML elements
Easier to changed Application Logic
Faster Loading (HTML is not going from Parser->Browser it goes straight to browser)
However some cons may be:
It only works in PHP5 (I Believe, could be wrong, correct if needed)
It may not be what one is used to
Untidy if done incorrectly (without indentation etc, however this is the same with anything)
But as you can see, the pros outweigh said cons. Try not to mix the two also, some separation and some intergration - this may get confusing for yourself and other developers that work with you.
I hope this helped.
Benefits of the first method (separating PHP and HTML):
You don't need to escape characters
It's also possible for code editors
to highlight/indent the markup.
It's arguably easier to read
There is no downside to this method,
compared to the second method.
Functionally: they both will work, so ultimately it is a preference.
Yet, you might consider that comments are a preference as well, your code would compile and run exactly the same without comments. However most people would agree comments are essential to writing and maintaining good code. I see this as being a similar subject matter. In the long run it will make it easier to read and maintain the code it if the two are separated.
So is it important? I would say Yes.
I kick off with: the first one you can open in a WYSIWYG editor, and still see some markup, which might makes it easier to maintain.
It says that what you put in echo '' it is first processed by the programming language and then sent to the browser, but if you directly put there html code without php, that code will load faster because there is no programming involved.
And the second reason as people above said is that you should have your 'large programming code' stored separately of the html code, and in the html code just put some calls to print results like 'echo $variable'. Or use a template engine like Smarty (like I do).
Best regards,
Alexandru.
Ouch!
All of the examples in your question are perfectly impossible to read. I'd say, you do yourself and those, who might read your code a great favour and use a template engine of sorts, say, Smarty. It is extremely easy to set up and use and it WILL separate your code from presentation. It doesn't require you to put everything in classes, it just makes sure, that your logic is in one file and presentation - in another one.
I don't know how in php but in asp.net separation has the following advantages.
1. separated code is easy to understand and develop
2. designer can work in html in the same time developer can write a code

Categories