0

I am looking for the safest way to sanitize user inputs and avoid security risks on a PHP online application.

Until now, I used TRIM + mysqli_real_escape_string in order to clean whitespaces and sanitizing content, as this (string data):

$ca_title = trim(mysqli_real_escape_string($con,$_POST['ca_name']));

Due to the continuous "do not access superglobal $_post array directly" Netbeans advice, I searched about this and found another way of sanitizing that I doubt if makes the same as I was making until now:

$ca_title = filter_input(INPUT_POST, 'ca_name', FILTER_SANITIZE_STRING);

After looking on PHP docs, I must say I don't find much difference between both, and so I can´t decline for the safest method. Could you advise me on this?

Biomehanika
  • 1,530
  • 1
  • 17
  • 45
  • Best, according to which criteria? – Hannes Johansson Sep 23 '15 at 14:09
  • To the main sanitizing objective: create a safe backend free of injections – Biomehanika Sep 23 '15 at 14:10
  • @HannesJohansson I found this, guess is one of the best questions about this: http://stackoverflow.com/questions/15102796/when-to-use-filter-input – Biomehanika Sep 23 '15 at 14:22
  • When you pass the data from your view to your controller you would only need to use $_POST once, and from there on - in the controller - use the method's parameter (which is the aliased $_POST array). Eliminating over usage of $_POST. Also, Netbeans will be happy again. – Ben Fransen Sep 23 '15 at 14:46
  • 1
    You are using MySQLi - why don't you use prepared statements? You can even stick the stuff from `$_POST` and never worry about a thing. Also, why trim before insert? I usually keep the original string intact and manipulate it once I fetch it from the db - that way I can do whatever I want with it at any point. – Mjh Sep 23 '15 at 14:49

2 Answers2

1

They do different things.

Always escape data for your database. This is best done with prepared statements.

Always escape text before inserting it into HTML (htmlspecialchars is the basic tools here).

Always (unless you absolutely trust your users to be both not-malicious and capable of writing quality HTML) use a DOM aware whitelisting XSS filter on inputted HTML before inserting it into your HTML documents.

Use filters (in addition to the above) when it would never make sense to have certain characters in the data (e.g. non-numbers in a telephone number). Make sure your preconceptions are correct first though.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Instead of filtering/sanitizing, use mysqli's preprared statements. Those are safe to execute regardless of the content of the parameter, and need no cumbersome and error-prone escaping/un-escaping.

adhominem
  • 1,104
  • 9
  • 24