-1

I have a comment system in PHP, and when a user types a line break in the textarea it shows up as rn (Note: I'm sanitizing this input and using htmlentities(), and I have custom mark-up).

Here's my current code (including attempt at line break replacement):

$comment_content =stripslashes(str_replace('\r\n', '@//', mysql_real_escape_string($_POST['comment_content'])));
$comment_content = htmlentities($comment_content);
$comment_content = mysql_real_escape_string(str_replace("====", "<span class=".$bold.">", $comment_content));
$comment_content = mysql_real_escape_string(str_replace("===", "</span>", $comment_content));
$comment_content = mysql_real_escape_string(str_replace("~~~", "<span class=".$italic.">", $comment_content));
$comment_content = mysql_real_escape_string(str_replace("~~", "</span>", $comment_content));
$comment_content = mysql_real_escape_string(str_replace("++++", "<span class=".$big.">", $comment_content));
$comment_content = mysql_real_escape_string(str_replace("+++", "</span>", $comment_content));
$comment_content = mysql_real_escape_string(str_replace("___", "<span class=".$underline.">", $comment_content));
$comment_content = mysql_real_escape_string(str_replace("__", "</span>", $comment_content));
$comment_content = mysql_real_escape_string(str_replace("@//", "<br>", $comment_content));
$comment_content = comment_sanitize($comment_content);

And this is how I sanitize:

function sanitize($sql, $formUse = true) {
    $sql = preg_replace("/(from|script|src|select|insert|delete|where|drop table|show tables|`|,|'|\*|\\\\)/i","",$sql);
    $sql = trim($sql);
    if(!$formUse || !get_magic_quotes_gpc()) {
        $sql = addslashes($sql);
    }
    return $sql;
}

Any ideas?

zbee
  • 959
  • 1
  • 7
  • 29

1 Answers1

1

You don't use htmlentities on the way in, you use it on the output. You should be escaping to input into your database and then to display newlines on the output consider:

nl2br(htmlentities($comment));
Martin
  • 6,632
  • 4
  • 25
  • 28
  • Well, see, the thing is, I have my own mark-up for this comment system, and it changed something like ~~~Underline Text~~ to Underline Text. I'll post my code in a bit so you can see what I mean. – zbee Jan 30 '13 at 17:56
  • @Zbee if you perform the nl2br/htmlentities first you can still do all of your replacements and they wont be escaped prior to output. – Martin Jan 30 '13 at 17:59
  • So, if I have Span-ness in my database as a comment and echo that comment as htmlentitites($comment) it would simply echo "Span-ness" in a tag? – zbee Jan 30 '13 at 18:02
  • @Zbee I would recommend doing the replacement after the `SELECT` not before the `INSERT`.. That way you can tweak your styling without a major headache at a later date – Martin Jan 30 '13 at 18:07