So basically I’ve been digging deep into the realm of MySQL and PHP…specifically the security measures I should take when dealing with a database and form inputs. So far I’ve found that the following are very strongly recommended:
- Prepared Statements
- Using mysqli_real_escape_string()
- NOT using Magic Quotes as it confuses databases and ends up giving you stuff like “You\’re name isn\’t….”
All of this is great and I’ve been following it. However, I was wondering if one should also escape characters such as the dollars sign [$], percentage sign [%], and possibly others. Couldn’t the query interpret the dollar sign as a PHP variable perhaps? What about LIKE syntax I’ve heard that uses the % symbol or even the wildcard sign? Prepared statements should technically take care of all of this, but I just wanted to be safe and make sure I had everything escaped properly. In the case that I forget to use prepared statements or just neglect to do them, I was hoping this second line of defense per-say could save me a loooong headache.
Here is what I use for escaping currently:
function escape($connection, $data){
$new_data = trim($data);
$new_data = mysqli_real_escape_string($connection, $new_data);
$new_data = addcslashes($new_data, '%_$');
$new_data = htmlspecialchars($new_data, ENT_NOQUOTES);
return $new_data;
}
So is this proper? Am I doing something horrendously wrong? Notice that I would have to remove back slashes before the $, %, and _ characters when retreiving the database data.