On 11/9/05 6:21 PM, Ross wrote:
What is the correct syntax for
$query = "SELECT * FROM login where username='$_POST['username']' AND pass
='$_POST['pass']'";
Thought this would work.
R.
The correct syntax in this case is actually:
$query = "SELECT * FROM login where username='{$_POST['username']}' AND
pass='{$_POST['pass']}'";
Note the curly braces.
BUT! Never do this!
For example, consider if someone typed in their username like this:
foo' AND 1=1 --
The "--" in most database engines starts a comment, so the query would
end up being:
SELECT * FROM login where username='foo' AND 1=1 --' AND pass=''
Everything after the "--" is ignored. There doesn't have to be a user
named "foo" because 1 will always equal 1, so the user is instantly
logged in.
Instead, filter your input (data received) and escape your output (in
this case, data going to the database), and try something like this:
<?php
$clean = array();
$sql = array();
if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}
if (ctype_alnum($_POST['pass']))
{
$clean['pass'] = $_POST['pass'];
}
if (isset($clean['username']))
{
$sql['username'] = mysql_real_escape_string($clean['username']);
}
if (isset($clean['pass']))
{
$sql['pass'] = mysql_real_escape_string($clean['pass']);
}
$query = "SELECT * FROM login where username='{$sql['username']}' AND
pass='{$sql['pass']}'";
?>
Everything in $_POST should be treated as tainted data. Everything in
$clean can be treated as valid and untainted. This ensures that the
username and password received only contain values that you expect. You
can modify the filtering to suit your needs. Then, it ensures that data
sent to the database in the SQL statement is always escaped so that it
doesn't try to do something it shouldn't.
This, of course, assumes you're using MySQL, but there are other
escaping functions for other databases. Just look in the PHP manual.
--
Ben Ramsey
http://benramsey.com/
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php