0

I'm having an issue with some HTML that I'm decoding and then displaying.

I post data from a WYSIWYG text editor called TinyMCE and store it into a database using the following code (with unrelated code not included)

$text = $_POST['bbcode_field']; // from textarea
if(get_magic_quotes_gpc()){
     $text = stripslashes($text);
     //strip off the slashes if they are magically added.
}
$text = htmlentities($text);

I then enter the data into the database using the following

Report ='".htmlspecialchars(mysql_real_escape_string($text), ENT_QUOTES)."',

Which is great, it inserts into the database perfectly fine. When I then try to retrieve the data from the database and decode it using

'.html_entity_decode($row['Content']).'

and echo it out, it's echoes it out but includes the HTML formatting such as <p> tags etc.

I need to be displayed on the HTML page but using the formatting of the HTML tags.

Where have I gone wrong here?

Thanks.

Steve
  • 20,703
  • 5
  • 41
  • 67
Thody
  • 139
  • 9
  • 1
    Stop double and triple encoding your HTML and then decoding it again. Why are you doing that in the first place? – deceze Sep 26 '14 at 14:48

1 Answers1

0

Delete this:

$text = htmlentities($text);

And the marked parts here:

Report ='".htmlspecialchars(mysql_real_escape_string($text), ENT_QUOTES)."',
           ^^^^^^^^^^^^^^^^^                               ^^^^^^^^^^^^^

And this:

html_entity_decode($row['Content'])

The problem is that you're encoding your HTML entities twice, but are decoding them only once. That means they end up encoded once, and of course won't be interpreted as HTML (which is the point of encoding them). When in fact, you don't need or want to encode them at all.

If you're accepting arbitrary HTML from your clients though, you'll want to filter it to avoid HTML injection. Have a good look at http://htmlpurifier.org.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • If I don't keep the ENT_QUOTES then I can't put single or double quotation marks in the text as they mess up the query. Is there a way around this? – Thody Sep 26 '14 at 19:09
  • You're already doing it by SQL escaping. See http://stackoverflow.com/q/60174/476. Also see http://kunststube.net/escapism – deceze Sep 26 '14 at 20:03