Someone is playing with my site url. Real URL is : baby_of_the_day.php?cusid=2639&bdate=2008-11-12 Modified URL: baby_of_the_day.php?cusid=-1+UNION+SELECT+0x73716C696E6A666C6431,0x73716C696E6A666C6432,0x73716C696E6A666C6433,0x73716C696E6A666C6434,0x73716C696E6A666C6435,0x73716C696E6A666C6436,0x73716C696E6A666C6437,0x73716C696E6A666C6438-- I found this url in error logs. My question is what he is trying to do using above query in url and most importantly how can I prevent this type of queries to MySQL Server using PHP. Waiting for some good replies.
Basic validations does go a long way. For example if custid is an integer then cast it to an integer. Casting it will remove all the alpha characters. On my scripts if I know the variable is numerical and I get something besides numbers then I stop the script.
Whoever is trying to modify the URL is trying a MySQL injection technique. As SGBoise said - basic validations go a long way. If you're expecting a number from the URL then use intval() to convert it to an integer - see thuankkk's reply. As for handling strings there's an annoying thing in PHP called the magic GPC . Fortunately this has been removed from PHP 6 as it caused more problems than it solved but you can disable it and use mysql_escape_string() on every string you want to add to your database. Easy to do with a .htaccess file which is what I do.
that problem was called sql injection. use this code at the beginning of the file. or... just create a single file for it and include it in each other php file (which receive get or post parameter) foreach($_GET as $key => $val) { $_GET[$key] = mysql_escape_string(strip_tags(stripslashes($val))); } foreach($_POST as $key => $val) { $_POST[$key] = mysql_escape_string(strip_tags(stripslashes($val))); } PHP: hope it works!
Forget loops. The code must be ran after a mysql_connection, it works recursively through MDs too. $connection is a reference to the MySQL connection. <?php $connection = mysql_connect(); array_walk_recursive($_GET, create_function('&$value, $key, &$connection', '$value = mysql_real_escape_string(strip_tags(stripslashes($value)), $connection);'), $connection); print_r($_GET); // Example ?> PHP: