Afik Habaz
Afik Habaz

Reputation: 79

Should i use 'strip_tags() ' before inserting into database or before printing on page?

I am following various steps to prevent any kind of injections or attacks on my web application. While I was following them a question came to my head: One of the very basic actions to take to prevent attacks on your web app is to prevent the user from writing malicious scripts that could possibly hurt the other users. In the sources I've read it said that you should use strip_tags() or htmlentities() but it wasn't clear enough if I should put it before I am inserting the user data into the database or before I am printing it out or maybe both..

So basically my question is when do I use these functions? And also what if I want to keep some of the html tags?{In case I am using a html text editor} and is it recommended at all?

Upvotes: 2

Views: 1626

Answers (2)

francovici
francovici

Reputation: 546

strip_tags() is used as a security measure to prevent XSS (Cross Site Scripting) attacks.

You should use it when you're recieving data to process on your site. Generally you could use it when you handle POST and GET variables from site to site.

e.g.

If you have a login form on a login.php site, you will handle the POST or GET action of that form on a different (or the same) site.

Inside those POST or GET variables there could be XSS attacks like:

<script>alert('Hi. This is a cyberattack');</script>

What you want to do with strip_tags() is to remove the unwanted tags from those variables.

You could allow wanted tags inside a custom function, but that's up to you.

Upvotes: 0

Dharman
Dharman

Reputation: 33400

strip_tags() is used to sanitize the data you receive from the users. It will try to remove all NULL bytes, HTML and PHP tags. Personally I am not a fan of this function as there are better ways to validate and sanitize input, e.g filter-input.
If you would like to keep some HTML you could take a look at http://htmlpurifier.org/

htmlentities() is used to output data into HTML context. If you are displaying anything in HTML (doesn't matter where the data comes from) you should use this to prevent XSS. More information

To prevent SQL injections you should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. If you make sure to never mix data and SQL you can insert any data you would like to DB, even other SQL.

They all have different uses and prevent different kind of bugs.

Upvotes: 5

Related Questions