James
James

Reputation: 2033

PHP XSS Question / Clarification

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.

Upvotes: 6

Views: 382

Answers (3)

Erlend
Erlend

Reputation: 4416

Please check the OWASP XSS Prevention Cheat Sheet. It will explain how to avoid XSS for different contexts. Htmlentities should do the job when between tags.

Upvotes: 0

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

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).

Upvotes: 3

knittl
knittl

Reputation: 265211

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)

Upvotes: 3

Related Questions