gamefreak13 Posted May 23, 2008 Share Posted May 23, 2008 I am so sick of reading about sql injection. Every article recommends a different way of preventing sql injection. There has to be a final answer. An answer that works in all scenarios and has no negative impact and doesn't require a step before and after (e.g. add/strip slashes). A few include: addslashes stripslashes trim mysql_real_escape_string strip_tags htmlentities So what is it? If I understand things correctly, mysql_real_escape_string is the best single one to use but isn't perfect. So what is the perfect combination? I am trying to sanitize user input for registration/login which queries my database. The site is more likely than most to receive script kiddies trying to do harm, so I'd like to figure this out before I release the site. Also.. this is what I have right now (found this snippet online). Why would I need to to use stripslashes? If anything, wouldn't I need addslashes instead? function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } Link to comment https://forums.phpfreaks.com/topic/106902-how-to-sanitize-user-input-to-prevent-sql-injection/ Share on other sites More sharing options...
micmania1 Posted May 23, 2008 Share Posted May 23, 2008 How you avoid injctions is your own choice based on the best output for what you need. You could create a function which would keep all input constant throughout your site. function escape_string($string) { $string = htmlspecialchars(mysql_real_escape_string)); return $string; } There is no right way to do it. Link to comment https://forums.phpfreaks.com/topic/106902-how-to-sanitize-user-input-to-prevent-sql-injection/#findComment-547954 Share on other sites More sharing options...
gamefreak13 Posted May 23, 2008 Author Share Posted May 23, 2008 I guess I need to create two different filter functions. One to filter so I put the user input in to a sql query (remove slashes and stuff). The other is to filter the input that is shown on the page (remove html stuff). This is what I got for the sql portion. Opinions welcome. function clean($string) { // IF MAGIC_QUOTES_GPC IS ENABLED WE MUST STRIPSLASHES if(get_magic_quotes_gpc()) { $string = stripslashes($string); } // IF MYSQL_REAL_ESCAPE_STRING IS AVAILABLE, USE IT! if(function_exists("mysql_real_escape_string")) { $value = mysql_real_escape_string($string); } // FOR PHP VERSION < 4.3.0 USE ADDSLASHES else { $value = addslashes($string); } return trim($string); } Link to comment https://forums.phpfreaks.com/topic/106902-how-to-sanitize-user-input-to-prevent-sql-injection/#findComment-547995 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.