CHAPTER 5 – SQL Injection

SQL Injection is a method in which an attacker inserts malicious code into queries that run on your database. Have a look at this example: <?php $query = "SELECT login_id FROM users WHERE user='$user' AND pwd='$pw'"; mysql_query($query); ?> VoilĂ ! Anyone can log in as any user, using a query string like http:// e x a m p l e . c o m / l o g i n . p h p ? u s e r = a d m i n ' % 2 0 O R % 2 0 ( u s e r = ' & p w d = ' ) %20OR%20user=', which effectively calls the following statements: <?php $query = "SELECT login_id FROM users WHERE user='admin' OR (user = '' AND pwd='') OR user=''"; mysql_query($query); ?> It's even simpler with the URL http://example.com/login.php? user=admin'%23, which executes the query SELECT login_id FROM users WHERE user='admin'#' AND pwd=''. Note that the # marks the beginning of a comment in SQL. Again, it's a simple attack. Fortunately, it's also easy to prevent. You can sanitize the input using the addslashes() function that adds a slash before every single quote ('), double quote ("), backslash (), and NUL (). Other functions are available to sanitize input, such as strip_tags().

Post Comment
Login to post comments