SQL injection

SQL injection

Description

Request values inserted into SQL passed to mysqli_query, query or exec can be interpreted as SQL syntax.

Potential impact

Access checks may be bypassed, and records may be exposed, changed or deleted within the database account’s privileges.

Remediation

Prepare the statement with PDO or mysqli and bind request values as parameters. Choose dynamic table or column names from an allow-list defined in code.

Examples

Before

php
<?php
$id = $_REQUEST['id'];
$query = "SELECT * FROM users WHERE user_id = '$id'";
mysqli_query($db, $query);

After

php
<?php
$id = intval($_REQUEST['id']);
$stmt = $pdo->prepare('SELECT * FROM users WHERE user_id = :id');
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

The PDO example binds :id as PDO::PARAM_INT. Validate the ID’s format and range before calling intval, which converts the value to an integer.

References