2

I was reading an article about form security because I have a form in which a user can add messages.

I read that it was best to use strip_tags(), htmlspecialchars() and nl2br(). Somewhere else it is being said to use html_entity_decode().

I have this code in my page which takes the user input

<?php 
    $topicmessage = check_input($_POST['message']); //protect against SQLinjection
    $topicmessage = strip_tags($topicmessage, "<p><a><span>");
    $topicmessage = htmlspecialchars($topicmessage);
    $topicmessage = nl2br($topicmessage);
?>

but when i echo the message, it's all on one line and it appears that the breaks have been removed by the strip_tags and not put back by nl2br().

To me, that makes sense why it does that, because if the break has been removed, how does it know where to put it back (or does it)?

Anyway, i'm looking for a way where i can protect my form for being used to try and hack the site like using javascript in the form.

AdRock
  • 2,959
  • 10
  • 66
  • 106

3 Answers3

9

You have 2 choices:

  1. Allow absolutely no HTML. Use strip_tags() with NO allowed tags, or htmlspecialchars() to escape any tags that may be in there.

  2. Allow HTML, but you need to sanitize the HTML. This is NOT something you can do with strip_tags. Use a library (Such as HTMLPurifier)...

ircmaxell
  • 163,128
  • 34
  • 264
  • 314
0

You just need htmlspecialchars before printing form content, and mysql_real_escape before posting into SQL(you don't need it before printing), and you should be good.

Doing your way of stipping tags is very dangerous, you need short list of allowed tags with limited attributes - this is not something you can do in 1 line. You might want to look into HTML normalizers, like Tidy.

BarsMonster
  • 6,483
  • 2
  • 34
  • 47
  • 1
    I really see no harm in using mysql_real_escape(). Is there any reason for your statement? – marekventur May 14 '11 at 15:17
  • @marekventur 6 years later, but yes, there is a reason, mysql_real_escape() is not actually certain to be secure, as the sql statement will still be concatenated. The ***only*** way to protect against sql injection is to use parameterized statements. That's all. Any solution that rely on escaping values and concatenating strings will be hacked some day. – Félix Adriyel Gagnon-Grenier Nov 05 '18 at 18:12
  • @FélixGagnon-Grenier You are completely right now. Anyone using deprecated mysql interface in 2018 is asking for trouble. – BarsMonster Nov 05 '18 at 19:57
-1
  • Use HTML Purifier for html-input and strip everything you dont want - all but paragraphs, all anchors etc.

Unrelated but important:

handfix
  • 134
  • 1
  • 1
  • 6