note 48065 deleted from security.database.sql-injection by bjori
| From: | bjori@php.net | Date: | Wed, 12 Apr 2006 15:04:37 +0000 |
| Subject: | note 48065 deleted from security.database.sql-injection by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-107888@lists.php.net to get a copy of this message | ||
Note Submitter: Jones at example dot com
----
I use the following funktion to avoid such things:
<?php
function prepareSQL($queryString, $paramArr) {
foreach (array_keys($paramArr) as $paramName) {
if (is_int($paramArr[$paramName])) {
$paramArr[$paramName] = (int)$paramArr[$paramName];
}
elseif (is_numeric($paramArr[$paramName])) {
$paramArr[$paramName] = (float)$paramArr[$paramName];
}
elseif (($paramArr[$paramName] != 'NULL') and ($paramArr[$paramName] != 'NOT
NULL')) {
$paramArr[$paramName] = mysql_real_escape_string(stripslashes($paramArr[$paramName]));
$paramArr[$paramName] = '\''.$paramArr[$paramName].'\'';
}
}
return preg_replace('/\{(.*?)\}/ei','$paramArr[\'$1\']',
$queryString);
}
$sqlQuery = 'SELECT col1, col2 FROM tab1 WHERE col1 = {1} AND col3 = {2} LIMIT {3}';
$stm = mysql_query(prepareSQL($sqlQuery, array('username', 24.3, 20);
?>
So everything that's not NULL, NOT NULL, an integer or a float/double will be escaped with
MySQL's mysql_real_escape_string and putted into '
A problem is if e.g. an user gives an "hacked" variable for the LIMIT-Clause - than the
function whould return something like this
SELECT .... LIMIT '0; DELETE FROM users'
So mysql whould produce an error - but better than deleting the users table ;)