1

I have been using this code on my website for a long time, and just want to make sure I am correctly sanatizing my PHP $_POST inputs...

foreach($_POST as $key=>$val) //this code will sanitize your inputs.
  $_POST[$key] = mysqli_real_escape_string($connection, $val);

Say for example I had the POST value $_POST['comment'] that I wanted to add to a database, would this be a good and safe way to sanatize it before database entry?

foreach($_POST as $key=>$val) //this code will sanitize your inputs.
  $_POST[$key] = mysqli_real_escape_string($connection, $val);

  //is this safe? or is there another step?
  $comment = $_POST['comment'];

  if($comment != ""){
  //add $comment to database
  }

Is there something that I still need to do before adding $comment to the MYSQL database? Or do those top two lines do the magic by themselves? Please let me know if this is a good safe way to do it, or if there is an even better way! Thanks!

pattyd
  • 5,927
  • 11
  • 38
  • 57

6 Answers6

2

Possible duplicate of: https://stackoverflow.com/questions/15664021/php-escaping-vars-posted-through-var-and-got-by-postvari-with-a-meth

I already tried your way. It seems there's no magic function. However, from classic MySQL injections, you can be safe, when adding mysqli_real_escape_string to each posted value, then use it as a string (quoted) in the db, but it's considered bad practice, also is not the most secure way

Since MySQLi presents parametised queries, you should get familiar with them, and leave the real corresponding to the database driver, to the library.

Community
  • 1
  • 1
Royal Bg
  • 6,988
  • 1
  • 18
  • 24
  • that helps, thanks! I will do a bit of research! I will accept answer in one minute – pattyd May 20 '13 at 22:41
  • +1 for parameterized queries. Calling the escape functions by hand is a sign you're doing something wrong. – tadman May 20 '13 at 23:37
1

It's not. One can use multibyte attacks, which will bypass all these sanitizers.

Moreover,

According to this answer one should avoid writing to post so one can keep sanitized code far from un-sanitized. Even though you "sanitize" everything, it leads to bad habits.

Community
  • 1
  • 1
1

This is not a good way to sanitize input. Queries should be parameterized and input should be fed as arguments no matter where it comes from. No additional sanitation should be done (otherwise it could be duplicated).

If you have specific rules (such as $comment != "") this is validation, and it is up to you to decide validation rules and how to handle invalid input (which is different than unsanitized input).

Example of using properly parameterized prepared statement with mysqli:

$stmt = mysqli_prepare($connection, "INSERT INTO comments VALUES (?)");
mysqli_stmt_bind_param($stmt "s", $comment);
mysqli_execute($stmt);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 3
    It's important to note here that sanitization is done *only* at the point of query execution. Doing it prematurely leads to all kinds of problems. – tadman May 20 '13 at 22:34
  • @tadman I did not that, but it is important to highlight it – Explosion Pills May 20 '13 at 22:35
  • @tadman Noob question, but your saying that using functions like filter_var are not a "good practice" for safe php? If you could take a look at my answer below and comment on it that would be great. – Rixhers Ajazi May 20 '13 at 22:53
  • @RixhersAjazi depends on what they are used for. If we are talking about sanitation of arguments for a query to prevent injection, I don't see how `filter_var` would fit in, but it could be very useful for validation (which is still important) and possibly other security concerns depending on the specifics – Explosion Pills May 20 '13 at 22:54
  • @ExplosionPills Yea, your very right... I am thinking of filter_var as a way oh helping to create safer user input to help mitigate the chance of XSS. I've just always used the filter_var functions to be safe. – Rixhers Ajazi May 20 '13 at 22:58
0

_real_escape_string does not sanitize user inputs completely. You must use prepared statements.

Object oriented style

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

Procedural style

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

Parameter types

Character     Description
i   corresponding variable has type integer
d   corresponding variable has type double
s   corresponding variable has type string
b   corresponding variable is a blob and will be sent in packets

Documentation

Kermit
  • 33,827
  • 13
  • 85
  • 121
  • 1
    `mysql_real_escape_string`, while ugly and deprecated, does technically sanitize them correctly. – tadman May 20 '13 at 22:33
  • @tadman [Not according to this](http://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html) – Kermit May 21 '13 at 00:46
  • It does have known limitations, which is why `mysql_query` needs to go away, you're right there. – tadman May 21 '13 at 01:40
  • @tadman Doesn't matter the API; prepared statements should be used period. – Kermit May 21 '13 at 01:46
0

down side is that you maim the post vars so you cant use them for other purposes than queries. for example what if you still wanted to echo out some post vars?

better is to escape to a new array

and even better is to not escaped but use parameterized queries.

nl-x
  • 11,762
  • 7
  • 33
  • 61
0

Your missing some of the most important things to safe PHP coding.

Lets start from the beginning.

Start with these links please : Please read the code comments

This first // and this second!

1) Validate and then filter your data if it passes validation!

So we have a registration form, one that takes emails... so now what we do is validate the email.

$email = $_POST['email']; // Declare the variable
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // If validation passes ... 
    $safe_email = filter_var($email, FILTER_SANITIZE_EMAIL) // Sanitize the email
} else { // Validation fails no need to sanitize
    echo "WRONG EMAIL PUNK!!!!";
}

2) Now using either Mysqli or PDO (I prefer PDO) we do :

$dbh = new PDO("mysql:host=xxxxxx;dbname=xxxxxx;charset=utf8", USERNAME(XXXXXXXXX), PASSWORD(XXXXXXXX); // Set up the PDO instance PLEASE DO NOT FORGET TO EXPLICETELY STATE A CHARSET!!!!
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set up error mode
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // I prefer emulate prepares to be false

$sql = INSERT INTO ..... (........., email) VALUES (............, :email); // Set up our named parameter
$query -> $dbh -> prepare($sql); // Prepare the query 
$query -> bindParam (':email', $email);
$query -> execute() // Yay!

Its all fine and dandy using PDO and MysqlI but there is an expression called :

Its not the wand, its the wizard. 

PDO / MysqlI can not solve everything! Make sure to

Refer to my other question on how to set up PDO

1) Validate 2) Sanitize 3) use parameters for safer queries! 4) Escape any outside (un-trusted data)

Follow these security PHP practices for safer php coding.

Enjoy

Community
  • 1
  • 1
Rixhers Ajazi
  • 1,303
  • 11
  • 18
  • A lot of what's present here is the anti-pattern of not using a proper ORM. Data validation should be done in a consistent manner and encapsulated in a proper structure so as to be re-usable. Having a line of code like `filter_var($email, ...)` is not a very portable way of doing this. At least you've got PDO set up properly and are using the named placeholders feature to make it clear that everything is being properly escaped at the time of execution. – tadman May 20 '13 at 23:37
  • Well the proper way would be to create functions that do this, no? Again I'm only asking as you seem to know more about the filter_var function. – Rixhers Ajazi May 20 '13 at 23:46
  • The proper way would be to use an ORM and have consistent, testable methods for cleaning, validating, and persisting user input. Writing arbitrary functions to clean things is only going to work for trivial programs. Anything bigger than that needs more structure, and an ORM provides that. There are many to choose from. Pick one that fits your needs. – tadman May 21 '13 at 01:44