Hello.
Is it safe to store XHTML code in a database?
What I usually do is store XHTML in the database and then just use htmlspecialchars() when outputting it on the website.
Is that a safe practise or are there any security risks?
| SitePoint Sponsor |




Hello.
Is it safe to store XHTML code in a database?
What I usually do is store XHTML in the database and then just use htmlspecialchars() when outputting it on the website.
Is that a safe practise or are there any security risks?
Do you want to output the (X)HTML to show to the user, or as part of the site's (X)HTML?
Jake Arkinstall
"Sometimes you don't need to reinvent the wheel;
Sometimes its enough to make that wheel more rounded"-Molona








To clarify, yes and no... Sometimes I want to display XHTML to the users (I do that with htmlspecialchars()) but sometimes I just want to incorporate it in the website...
I guess only the latter poses security threat (XSS)?
Correct. The former, if escaped, will be perfectly fine because the escaped tags will not be executed.
The latter does have a bit of an issue. What I would recommend is that you scan all links and images for sources of javascript, and obviously remove script and maybe style tags.
You would run that when the page is being displayed, but of course that adds to load. Another solution would be to run it when things are inserted or updated, but that leaves you more vulnerable if someone gains DB access. Another solution maybe to run a cronjob quite often which searches for any rows with '<script', 'href="javascript:"' etc tags.
Jake Arkinstall
"Sometimes you don't need to reinvent the wheel;
Sometimes its enough to make that wheel more rounded"-Molona




Looks good.
Of course you'd need precautions in place just in the case of someone gaining direct access to the database...
Jake Arkinstall
"Sometimes you don't need to reinvent the wheel;
Sometimes its enough to make that wheel more rounded"-Molona





I think there's some confusion between storing the XHTML in the database and outputting it. You don't have to purify it or do anything to the XHTML when you put it into the database because the database does not care. It will not act on it. When you output it, the browser does care, because it will parse the XHTML. That means that you can purifier the XHTML either before or after you store it in the database.
With proper security practices, you shouldn't need to take those precautions. You probably have bigger problems on your hands if that happens.
Bookmarks