jannes braet
jannes braet

Reputation: 1

How do I sanitize data from users before sending it to mySQL?

I am making a forum at this moment.

I would like to sanitize my input data (that is, the posts from users) before sending it to the MySQL database.

I already have been searching some functions to do that, but I'm not sure if I have used enough of them and if they're all secure enough. Any suggestions are welcome.

Here is the code I have:

$message=$_POST['answer'];
$message=nl2br($message); //adds breaks to my text
$message=stripslashes($message); //removes backslahes (needed for links and images)
$message=strip_tags($message, '<p><a><b><i><strong><em><code><sub><sup><img>'); //people can only use tags inside 2nd param
$message = mysql_real_escape_string($message); //removes mysql statements i think (not sure)

edit: Please tell me if I should add some tags to the strip_tags function. Maybe I have forgotten some.

Upvotes: 0

Views: 379

Answers (3)

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

If you want to allow limited HTML to be used in forum (as seen by the way you are using strip_tags()), use HTMLPurifier; otherwise you are vulnerable to javascript in attributes of those tags.

By the way, right now you are stripping the <br> tags you've added

Upvotes: 1

Igor Parra
Igor Parra

Reputation: 10348

When you save to DB:

$message=strip_tags($message, '<p><a><b><i><strong><em><code><sub><sup><img>'); //people can only use tags inside 2nd param
$message = mysql_real_escape_string($message); //removes mysql statements i think (not sure)

When you output:

$message=nl2br($message); //adds breaks to my text
$message=stripslashes($message); //removes backslahes (needed for links and images)

Besides, use htmlspecialchars when you write into html input elements like text or textarea

OBS: Don't reinvent the wheel. Learn some PHP framework like codeigniter that provides very secure ways to manage data. .

Upvotes: -1

Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Try using PDO instead. It has great binding function, which really improves security. Here's some examples: http://php.net/manual/pl/pdostatement.bindvalue.php

PDO is by default in PHP5, so pretty much everywhere these days.

Upvotes: 2

Related Questions