0

Can't use PDO.

I have read many questions here, this is my first time trying to do something for people outside my office, so I need to sanitize data input, researching about it found this function.

function clean_data($input){
$input = trim(htmlentities(strip_tags($input,",")));
if (get_magic_quotes_gpc())
$input = stripslashes($input);
$input = mysql_real_escape_string($input);
return $input;
}

example:

$vartodb = clean_data($_POST['yourformfieldhere']);

Its ok this function to sanitize data?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CCortina
  • 3
  • 2
  • This method is horrible and will break and mutilate data. Just sanitize data before it is going to be used, using the appropriate sanitation method. E.g. `mysql_real_escape_string()` before running `mysql_query()`. Or `htmlentities()` before outputting anything on a web page. But PDO or mysqli would really be beneficial – Pekka Nov 23 '13 at 14:02
  • so using this code im avoiding sql injection, `$sql = "INSERT INTO clientes VALUES (NULL,:iduser,:nombre,:cedula,:dir,:tel)"; $query = $db->prepare($sql); $query->execute(array( ':iduser'=>($_POST['id']), ':nombre'=>($_POST['nombre']), ':cedula'=>($_POST['cedula']), ':dir'=>($_POST['dir']), ':tel'=>($_POST['tel']), ))` – CCortina Nov 29 '13 at 05:23

2 Answers2

1

Not really.

If you are going to put the variable in a database, you would be better off using a prepared statement with bound variables. If you cannot use PDO, you can do that as well with mysqli. If you are really stuck with the mysql_* functions, you would only need mysql_real_escape_string.

If you output to the browser, you only need htmlspecialchars.

In short, there is no universal sanitizing function, you need to prepare / escape / encode your data for the medium you are outputting to.

jeroen
  • 91,079
  • 21
  • 114
  • 132
0

This is a vast topic - this function is ok but there are much better ways to do it.

Check mysqli_real_escape_string: http://php.net/manual/en/mysqli.real-escape-string.php

Don't forget prepared statements: http://php.net/manual/en/pdo.prepared-statements.php

Also, what if your input is of type integer? You should be typecasting.

Also, what if someone adds extra fields to your web form?

While this function does do some sanitisation it is only the tip of the iceberg, like I said it is a vast topic.

In my opinion this is sloppy code that offers little protection.

ddoor
  • 5,819
  • 9
  • 34
  • 41