views:

48

answers:

3
+1  Q: 

php form security

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

I read that it was best to use strip_tags(), htmlspecialchars() and nl2br()

Somewhere else 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, cos 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

A: 

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
-1 Don't use mysql_real_escape(); use parameterized queries.
tc.
+4  A: 

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
A: 
  • Use HTML Purifier for html-input and strip everything you dont want - all but paragraphs, all anchors etc.

Unrelated but important:

handfix
-1 Why won't people use parameterized queries?
tc.