0

I am building an app that would require users to input large chunks of text, like paragraphs at a time. I installed an editor (CKeditor) to offer users a nice interface to edit their text etc. The problem is that I can't sanitize the input before inserting in the database because it erases all the HTML and the text loses the paragraphs and other styling.

Is there a way to safely store that data and keep basic styling like paragraphs and maybe even text color?

Warlord
  • 2,798
  • 16
  • 21
  • Do you need HTML code for this, or could you possibly look into implementing something like BBCode? There are some WYSIWYG editors that have a BBCode plugin so you can sanitize the posts but keep styling. If you have some know-how in JS/jQuery you can easily implement your own WYSIWYG with BBCode as well. – lxndr Feb 18 '14 at 17:34
  • This is a duplicate of dozens of questions on StackOverflow. See http://stackoverflow.com/questions/5512712/sanitizing-html-input or http://stackoverflow.com/questions/2721184/php-html-sanitizer or http://stackoverflow.com/questions/2319956/are-there-any-good-php-based-html-filters-available or http://stackoverflow.com/questions/8442467/filter-html-on-php – Reinmar Feb 18 '14 at 18:17

1 Answers1

0

Here's what I've done. I've had to work with and build custom bulletin board and forum systems. When you have people trying to place stylized content, images, videos, smileys, etc... you need some form of content placement while also sanitizing the posts.

You have some options. My recommendation is to find an editor that has a BBCode plugin. When the posts come into your database, anything that has an HTML element will appear in brackets (i.e.; [ ]) instead of open/close tags. So if you wanted to bold something, you can use [B]bold this[/B]. You then do a simple function that strips these BBCode elements and replaces them with the proper HTML code.

Another thing you could do, which I don't recommend, but see happen, is str_replace all open and close tags with their html entities when you are inserting them into the database, and then str_replace all the respective html entities into the open and close tags when you are displaying the post.

The reason why I recommend BBCode or at least some sort of markdown is because you can completely shut down the users' ability to attack you with that post while letting them style their posts.

HTML BBCode Parser (Pear Package) - This will help you out if you go with the BBCode route.

CKEditor BBCode Plugin - You can just add this to your CKEditor WYSIWYG and run with it.

lxndr
  • 702
  • 1
  • 11
  • 25