Do I sanitize/escape correctly?

2019-03-07 03:03发布

问题:

I've made a simple search-script in PHP that searches a mySQL database and outputs the result. How this works is like this:

  • User searches for "jack's" through a search-form.
  • My PHP-script GETs this search, and sanitizes it.
  • Then the script, with the use of SELECT and LIKE, gets the results.
  • The script then outputs the result to the user.
  • Lastly, the script tells the user that "jack's returned x results." with the help of escaping.

What I would like to ask is, am I doing it right?

This is how I sanitize before SELECTING from the database:

if(isset($_GET['q'])){
  if(strlen(trim($_GET['q'])) >= 2){
    $q = trim(mysql_real_escape_string(addcslashes($_GET['q'], '%_')));
    $sql = "SELECT name, age, address FROM book WHERE name LIKE '%".$q."%'";
  }
}

And this is how I escape before outputting "jack's returned x results.":

echo htmlspecialchars(stripslashes($q)) . " returned x results.";

Is this the correct way to do it?

By the way, I know that PDO and mySQLi is preferred as they sanitize themselves through the use of prepared statements, but I have no real experience with them whatsoever. But I would gladly take a look, if you guys could link me some newbie tutorials/explanations. Furthermore, I heard that magic_quotes and charset could in some way or another lead to injections -- is this correct?

回答1:

For some reason we need also escape a backslash too.
So, the proper code would be, I believe

if(isset($_GET['q'])){
  $_GET['q'] = trim($_GET['q']);
  if(strlen($_GET['q']) >= 2){
    $q = $_GET['q'];
    $q = '%'.addCslashes($q, '\%_').'%';
    // now we have the value ready either for escaping or binding
    $q = mysql_real_escape_string($q);
    $sql = "SELECT name, age, address FROM book WHERE name LIKE '$q'";
    //or 
    $sql = "SELECT name, age, address FROM book WHERE name LIKE ?";
    $stm = $pdo->prepare($sql);
    $stm->execute(array($q));
    $data = $stm->fetchAll();
  }
}

For the output, use

echo htmlspecialchars($_GET['q']);

stripslashes not needed here.

Furthermore, I heard that magic_quotes and charset could in some way or another lead to injections -- is this correct?

magic quotes won't harm your security if you won't use them.
charset is dangerous in case of some extremely rare encodings but only if improperly set. if mysql(i)_set_charset or DSN (in case of PDO) were used for the purpose - you are safe again.

As for PDO, a tag wiki should be enough for starter, I believe