Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP XSS Question / Clarification

Tags:

php

xss

This has been asked before but I need 100% clarity on this issue as it's very important for me to get it right.

The situation: A message system on a website. The user enters a message into a text-box, they submit the form and it gets entered to the database. This data can then be called from the database and displayed within <span>tags to another user.

What security procedures do I need to take to prevent this data from being malicious? I already use the mysql_real_escape_string to stop any injection and strip_tags seems useful but I have heard lots of other names mentioned. What do I need to use to protect this data considering it is only displayed in <span> tags?

Thank you.

like image 962
James Avatar asked Sep 02 '11 16:09

James


2 Answers

The misconception is that you want to escape the input, which is wrong. You have to filter the output (and database is also an output).

It means that when the form is submitted, you use mysql_real_escape_string() to send (output) data to database, and you use htmlspecialchars() to output the content on the screen. The same principle applies to regular expressions, where you'd use preg_quote(), and so on.

No matter where data is coming from, you have to escape it in the context of where you are sending it to.

So for preventing XSS attacks, you must use htmlspecialchars() / htmlentities(). mysql_real_escape_string has nothing to do with XSS (but you still have to use it when you are sending data to the database).

like image 133
Maxim Krizhanovsky Avatar answered Oct 01 '22 23:10

Maxim Krizhanovsky


Use htmlspecialchars when outputting on an HTML page. It will display the data the same way the user entered it (so users can use something like <3 in their messages without stripping the rest of it)

like image 25
knittl Avatar answered Oct 01 '22 23:10

knittl