|
Posted by Mladen Gogala on 12/18/69 11:49
howachen@gmail.com wrote:
> Hi,
>
> In many web articles, people focusing on SQL injection in the form of :
>
>
> e.g.
> /**********************************************************/
> $name = "tom' UNION blah blah blah"
> $query = "SELECT * FROM users WHERE name = '".$name."';
> /**********************************************************/
>
> However, another form of SQL injection might in the form of...
>
> /**********************************************************/
> $name = "1 UNION blah blah blah"
> $query = "SELECT * FROM users WHERE id = ".$name;
> /**********************************************************/
>
> for case 1, we can easily solved by escaping the special characters
> like " ' ", but how to solve for case 2?
>
> Thanks.
>
This dynamic query forming is the root cause of the problem.
Here is how to solve it:
require_once ('adodb/adodb.inc.php');
require_once ('adodb/adodb-exceptions.inc.php');
$db = NewADOConnection("oci8");
$SQL="SELECT * FROM users WHERE name = :NAME";
try {
$db->Connect($DSN['database'], $DSN['username'],$DSN['password']);
$db->execute($SQL,array("NAME"=>$name));
}
catch(Exception $e) {
die($e->getMessage());
}
The only difference from your situation is the use of "oci8" driver
which is unlikely to work with MySQL. Everything else will work,
including placeholders. That way, you not only eliminate any possibility
for SQL injection but you also help the underlying database as it can
reuse previously parsed cursor. Entering SQL expressions will not have
any effect, as the variable is bound to a placeholder, not used to
create SQL dynamically.
--
Mladen Gogala
http://www.mgogala.com
[Back to original message]
|