PHP

PHP

Made by DeepSource

Audit required: SQL query might be vulnerable to injection attacks PHP-A1002

Security
Critical
a03 cwe-20 cwe-89 cwe-943 sans top 25 owasp top 10

Using user-provided data while executing an SQL query can lead to SQL injection attacks. An SQL injection attack consists of the insertion or "injection" of a malformed SQL query via the input data given to an application. It is a prevalent attack vector and causes significant damage if the incoming data is not properly sanitized.

In the past it has led to the following vulnerabilities:

If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.

Bad practice

function getUser() {
    $id = $_GET['id'];

    $query = "SELECT * FROM users WHERE id = '" . $id . "'";

    $conn = getConnection();
    $result = mysqli_query($conn, $query);

    $user = mysqli_fetch_array($result);

    return $user;
}

Recommended

function getUser() {
    $id = $_GET['id'];

    $mysqli = getConnection();

    $query = "SELECT * FROM users WHERE id = ':id'";

    $stmt = $mysqli->prepare($query);
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    $result = $stmt->get_result();

    return $result->fetch_assoc();
}

References