How to distinguish bigint to prevent SQL injection in php?

I am using php and doing sql queries on mysql server. to prevent sql injections, I use mysql_real_escape_string.

I also use (int) for casting numbers as follows:

$desired_age = 12;
$query = "select id from users where (age > ".(int)$desired_age.")";
$result = mysql_query($query);

which work.

But, when the variable contains large numbers, discarding them with an error, since they are more than int.

$user_id = 5633847511239487;
$query = "select age from users where (id = ".(int)$user_id.")";
$result = mysql_query($query);
// this will not produce the desired result, 
// since the user_id is actually being cast to int

Is there any other way to cast a large number (e.g. BIGINT), except using mysql_real_escape_string when it comes to preventing sql injection?

+3
source share
6 answers

You can use something like:

preg_replace('/[^0-9]/','',$user_id);

. , mysql_real_escape_string(), $.

+3

, MySQL, SQL- .

, filter_var() ( is_numeric()), , , .

+10

. , , . PHP-, , is_numeric() - ,

http://www.php.net/is_numeric

+1

, (, , xyz_real_escape_string()) / . MySQL lt; → number, / id, PHP-. (-) , id .

$pdo = new PDO('mysql:...');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$stmt = $pdo->prepare('SELECT age FROM users WHERE id=?');
$stmt->execute(array('5633847511239487'));
+1

private function escapeInt($value)
{
    if (is_float($value))
    {
        return number_format($value, 0, '.', ''); // may lose precision on big numbers
    }
    elseif(preg_match('/^-?[0-9]+$/', $value))
    {
        return (string)$value;
    }
    else
    {
        $this->error("Invalid value");
    }
}

, $i = 184467440737095; 32- , , .

0

*1, , ( bigint ... , , ? PDO .

0

Source: https://habr.com/ru/post/1753711/


All Articles