Re: SQL injection

From: Date: Fri, 17 Oct 2003 02:48:05 +0000
Subject: Re: SQL injection
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-166402@lists.php.net to get a copy of this message
Yann Larrivee wrote:
Hi i read many thing on sql injection but i just cant sumarize all the information. Most site (PHPadvisory.com, phpsecure.info, other found on google) dont talk to mutch on how to prevent SQL injection. At some place, they mentionned having a badword list, but really in a product description we can have about anyword (select, insert, update, ...) SO the badword liste is not really the solution i believe. I did the fallowing single quoted all the queries, parameters (even if numerical), did a mysql_real_eascape_string on all parameters befor they are passed to mysql.
This is pretty easy to prevent. You only need to be aware of two things, which I think you've already got. 1. You need to escape quotes in strings you pass to SQL queries. That means if you're passing a string delimited by single quotes, then single quotes must be escaped within that string (by whichever method is required by your database). $query = "UPDATE Table SET column = '$value'"; Since "column" is being passed a string delimited by single quotes (within the SQL, not within PHP!), all single quotes within $value must be escaped. addslashes() or mysql_real_escape_string() are two methods for accomplishing this. 2. If you're passing a value that is not within quotes, you must ensure the value is actually a number. This is most easily done by casting the value to an (int) or (float). $query = "UPDATE Table SET column = " . (int)$value; Using (int) or (float) will ensure value is a number and cannot contain any SQL injection attacks. Of course, you'll want to do this conversion, escaping, etc, in your validation functions. :) -- ---John Holmes... Amazon Wishlist: www.amazon.com/o/registry/3BEXC84AB3A5E/ php|architect: The Magazine for PHP Professionals – www.phparch.com

« previous php.general (#166402) next »