Re: sql injection attack, protection from

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



* Mayo <mayo@xxxxxxxxxxxxxxxxxx>:
> I'm new to PHP and would like to make certain that I have the basic
> protection for the site:
>  
> Use double quotes to contain variable

This depends entirely on the variable type expected by MySQL; int and
floats don't necessarily need quotes. However, it's typically a good
practice.

> Use mysql_escape_string so that query is considered part of the WHERE
> clause.

If you're on PHP >=4.3.0, use mysql_real_escape_string().

> $result=mysql_query('SELECT * FROM users WHERE
> username="'.mysql_escape_string($_GET['username']).'"');
>  
> I'm pulling prices from a database and sending the item ID which has 4
> characters (1001, 1002, etc.)
>  
> Is the following unnecessary with mysql_escape_string?
>  
> if (preg_match("/^\w{4,4}$/", $_GET['username'], $matches))
>    $result = mysql_query("SELECT * FROM items WHERE
> itemID=$matches[0]");
>  else // we don't bother querying the database
>    echo "itemID not accepted";

It's *always* better to filter your data before placing it in your
database. Check to see if the data is of the correct type and/or falls
within the correct range of values allowed for the field it will occupy.
Doing this will help keep your data normalized and prevent headaches
later on.

By the way, if you want some best practices for escaping data before
placing into a database, the manual page for mysql_real_escape_string
has some examples:

    http://php.net/mysql_real_escape_string

-- 
Matthew Weier O'Phinney           | WEBSITES:
Webmaster and IT Specialist       | http://www.garden.org
National Gardening Association    | http://www.kidsgardening.com
802-863-5251 x156                 | http://nationalgardenmonth.org
mailto:matthew@xxxxxxxxxx         | http://vermontbotanical.org

-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux