Vishal
Vishal

Reputation: 2181

Processing $_POST[] and $_GET[] variables

Currently I use this strategy:

After submitting a HTML form or data sent using jQuery's $.get() or $.post() I need to know what is come and then apply logic on the basis of that.

suppose, I've got $_POST['username'], $_POST['password'] and $_POST['login_submit_button']. In my processing script file, I do like this:

if(isset($_POST['login_submit_button']) && isset($_POST['username']) && $_POST['username'] != "" && isset($_POST['password']) && $_POST['password'] != "") {
  // calling a common function safe_vars() which does
  // mysql_real_escape_string(stripslashes(trim($any_variable_need_to_become_safe)))
  // and now using the above variables for different purposes like
  // calculation, insertion/updating old values in database etc.
}

I know all this logic is wrong or having serious issues, so I want a much-secure and perfect solution instead of this. I welcome to find out vulnerabilities and severe security-bleaches in my strategy. This question can help others too, if answers came more explanatory, this can be informative community wiki.

Upvotes: 2

Views: 182

Answers (2)

Quentin
Quentin

Reputation: 943097

There is no way to make a generic super "make things safe" function.

mysql_real_escape_string

You shouldn't use this at all. It uses the old mysql API, and assumes you are going to be manually smashing strings together to make SQL. Don't do that. Use PDO or mysqli and a function that deals in prepared queries and bound arguments.

stripslashes

This is an antidote to magic quotes. If magic quotes are not on it will destroy data. Don't use it. Turn magic quotes off instead.

trim

This destroys data. Don't use it unless you really want to remove white space at the start and end of the string.


Escape data for the target language immediately before inserting data into that language.

For SQL, use bound arguments and prepared queries.

For HTML, use htmlspecialchars or a template language that does escaping for you, such as mustache.

Alternatively, (if you want to allow HTML) parse it, generate a DOM, filter it using a whitelist, then serialise it back to HTML.

For JSON, use encode_json

etc.

Upvotes: 3

Ingmar Boddington
Ingmar Boddington

Reputation: 3500

  • You only need to stripslashes if you have magic_quotes enabled (use get_magic_quotes_gpc to check)
  • You should white list filter your POST vars using filter_var or ctype_* or preg_match (as well as checking bound conditions such as length and presence)
  • Use prepared statements / PDO for your queries to ensure proper escaping
  • Escape any html output with htmlentities

Nothing is bullet proof, however the above are good practices to avoid SQL injection / XSS.

Upvotes: 1

Related Questions