0

I have a javascript-based rich text editor.

What is the safest way to save the tags it generates?

I'm using MySQL as my database.

I'm not sure if using mysql_real_escape_string($text); is safe.

Serge Vinogradov
  • 710
  • 1
  • 9
  • 28
  • HTML in a database is not going to hurt. Issues arise when you create an application without a proper design. If the content has to be displayed as HTML, do not escape it. Otherwise, escape it before inserting it in the database. – Rob W Apr 11 '12 at 14:55
  • 2
    Look into `markdown` it is the method used on SO for questions & comments. I have found it much easier to work with (for users) than HTML, and less issues with validation of HTML and output. You store the markdown in the DB, which gets converted to valid HTML on output. – Jakub Apr 11 '12 at 14:57
  • @RobW I always got told _not_ to change the data that is being inserted and only alter the data when it comes out of the database? – Daan Timmer Apr 11 '12 at 15:15
  • @DaanTimmer You're generally correct (See also [this answer](http://stackoverflow.com/a/3023757?php-htmlentities-on-input-before-db-insert-instead-of-on-output)). – Rob W Apr 11 '12 at 15:25

2 Answers2

0

I'd recommend that you use mysqli to interface with the database, that way you don't need to escape data and get a complete protection against SQL injections. You may of course still need to protect against HTML injections.

You do not need to write the string of text to a JavaScript file. If you need it to be handled by JavaScript I suggest that you fetch the data using an XMLHttpRequest (which contrary to what the name suggests does not require your data to be in XML form).

aaaaaaaaaaaa
  • 3,630
  • 1
  • 24
  • 23
0

I can't think of a reason to use htmlentities here. mysql_real_escape_string is vital here because it prevents people from injecting malicious SQL code like ';DROP * FROM table foo;-- into you database. I'd try it without htmlentities, if you find that you need to convert to entities then you could try htmlspecialchars instead which only converts special characters.

If you want to limit the allowed HTML in your form you might also want to look into the strip_tags function.

Relevant documentation:
http://us2.php.net/manual/en/function.htmlentities.php
http://us2.php.net/manual/en/function.htmlspecialchars.php

Good luck

olleicua
  • 2,039
  • 2
  • 21
  • 33