Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP secure user variable

On my website I have a variable called $user_data that contains input from a form. I then show this variable on the user page (via echo).

What is the best method to avoid any security risks with this variable? I use strip_tags(), but it is not enough.

This variable also gets saved to a MySQL database.

like image 594
James Avatar asked Aug 21 '10 17:08

James


1 Answers

There are two very important things you must do to avoid serious security problems.

  1. You need to escape the user input before putting it in your SQL query. Escaping means escape all the special characters such as '; luckily, there is a function that already does it automatically: mysql_real_escape_string.

    If you don't escape user input nasty things could happen. Imagine that your query is INSERT INTO userdata VALUES ('$user_data'). Now imagine that the user wrote '; DROP DATABASE userdata;.

    If you don't escape it, your query will become: INSERT INTO userdata VALUES (''; DROP DATABASE userdata;'). As you can imagine this is not good: if you have multi statements enabled you can kiss goodbye to your database. This is called an SQL Injection attack.

  2. When you are outputting your variable to the user you also need to properly replace HTML special characters with HTML entities. Luckily, there is a function to do that too: htmlspecialchars(). It will transform the special HTML characters such as < to &lt;.

    This seems to be a problem that is often underestimated, but in reality it's very serious. Imagine if $user_data contains <script>SomeNastyScript()</script>. It could exploit existing vulnerabilities in the browser of your users, or it could send a non-HTTPOnly cookie (that may contain saved passwords) to the attacker, or it could trick the user into writing their password on a form generated through the manipulation of the DOM (possible in javascript), or a lot of other bad things.

    This is called XSS (Cross-site scripting).


Short version

  1. Call mysql_real_escape_string on the string before inserting it into your SQL query (but not when you echo it).

  2. Call htmlspecialchars on the string before displaying it to the user (but not when you put it in the database).

like image 60
Thomas Bonini Avatar answered Sep 18 '22 00:09

Thomas Bonini