mysql_real_escape_string()
mysql_real_escape_string() should always be used on data being placed into your SQL database. The function places backslashes before certain characters. That means if someone tried to insert an apostrophe ( ' ) into your SQL a backslash would be added ( \' ) so the apostrophe would be recognized as a character, not part of the script.$input = 'I'll be darned, this would have broke it.'; $data = mysql_real_escape_string($input);
htmlentities()
htmlentities() is one of my best friends. I learned about XSS early when I was a developer when a hacker posted JavaScript into a field and was able to snatch my admin cookie and deface my site. See, mysql_real_escape_string() may prevent SQL Injections but not XSS. htmlentities() will convert characters to their html entities. This will turn < or > into < or > preventing JavaScript from being inserted and executed on viewing.$input = '<script>javascript:alert("Alert");</script>' $data = htmlentities($input); //Returns <script>
str_replace()
At first I did not use htmlentities() but made my own function using str_replace() to replace characters to their HTML entities. I had one array containing the specific characters to be converted and the other array contained the HTML entities. This can be safer as htmlentities() does not convert all characters to HTML entities.$html = array("'", '"', '<', '>'); $entities = array(''', '"', '<', '>'); $data = str_replace($html, $entities, $input);
strtr()
strtr() is essentially the same as str_replace() but is faster. Also, instead using two arrays you can use just one array that uses pairs .$html = array('<' => '<', '>' => '>'); $data = strtr($input, $html);
Want more? Sign up for my weekly newsletter