amb99 Posted January 31, 2007 Share Posted January 31, 2007 Hi, I wanted to know if my current method is sufficient (or near sufficient) in preventing sql injection. I use this function. function clean($string) { $data = trim(strip_tags(htmlspecialchars(mysql_real_escape_string(stripslashes($string))))); return $data; } For both post/get vars, I first clear the variables. $post_some_var = ""; $get_some_var = ""; I then set them accordingly via the clean function. $post_some_var = clean($_POST['some_name']); $get_some_var = clean($_GET['some_name']); And then I use those variables in the mysql statements. $sql = "SELECT * FROM table WHERE something LIKE '%$get_some_var%'"; Most of everything I've been reading has been showing examples of using functions WITHIN the mysql statements, but going that route would be much harder on myself so I've been using this method instead. In your proffessional opinions, is this sufficient to prevent sql injection attacks? What changes, if any, should I make? Thank you for your help. Quote Link to comment Share on other sites More sharing options...
.josh Posted January 31, 2007 Share Posted January 31, 2007 for added protection, depending on the type of data you are expecting, you can have an array of allowed data and check if it specifically matches. for instance, if you have a dropdown in a form or a get var or something and let's say the options are colors, like red, green or blue. you could specifically check it like so: $allowed = array('red','green','blue'); $color = (in_array($_GET['color'], $allowed) ? $_GET['color'] : 'red'; // or some other default this obviously only applies to data that the user isn't supposed to enter some arbitrary thing. However, expanding on that principle, you should check for what IS expected. Is the user supposed to be entering in a url or email address? Do some regex to see if it's the right format. Some piece of info in the data that you are expecting it to contain? Check for it. etc... Quote Link to comment Share on other sites More sharing options...
tomfmason Posted January 31, 2007 Share Posted January 31, 2007 Here is an easier method for sanitizing an array like post, get or even request. $_POST = array_map('mysql_real_escape_string', $_POST); With that you sanitize the entire post array in one shot.. Now as far as sql injection you may want look into regex. Good luck, Quote Link to comment Share on other sites More sharing options...
Jessica Posted January 31, 2007 Share Posted January 31, 2007 strip_tags(htmlspecialchars You'll want to reverse these two, or no tags will ever be removed. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.