开发者

should i still sanitise input with mysqli?

I'm using mysqli prepare开发者_StackOverflow中文版d statements. Should I still sanitise the user input with some function like:

function sanitise($string){
  $string = strip_tags($string); // Remove HTML
  $string = htmlspecialchars($string); // Convert characters
  $string = trim(rtrim(ltrim($string))); // Remove spaces
  $string = mysql_real_escape_string($string); // Prevent SQL Injection
  return $string;
}

Thanks.


No! No and no. If you are already using prepared statements, MySQL needs to see the value, not some escaped version of it. If you add mysql_real_escape_string to a string and make that the value for a prepared statement, you have just junked it, for example, quotes get doubled up!

Now, as for sanitising data-wise, that's entirely up to the business rules as to what is or is not valid input. In your example, strip_tags is more about html->raw (format) conversion than sanitation. So is rtrim(ltrim - this is a business transformation.


Yes. When using prepared statements you are safe from mysql injections, but still there could be special characters, strip tags or spaces, so those you will still need to take care of those.

See PHP: Is mysql_real_escape_string sufficient for cleaning user input?

UPDATE:

You are safe from mysql injections so you should not use real_mysql_scape_string or scape any quotes.


Prepared statements are there to keep your query form being subverted by malicious input. But there's plenty of malicious content that is perfectly acceptable in an SQL query, but will attack a browser when redisplayed later.

Doing mysql_real_escape_string on data going into a prepared statement is generally redundant (there are exceptions, but they're special-ish cases).


Here is an Object orientated solution to your question:

public function sanitize($var){
    if(is_array($var))
        foreach($var as $k => $v) $var[$k] = $this->db->real_escape_string($v);
    else
        $var = $this->db->real_escape_string($var);
    return $var;
}


You should always sanitize your user inputs before submitting them to the database. I would just stick with mysql_real_escape_string as the others are not that much necessary unless you are putting them back on the URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜