2023-03-07 17:16:47 +01:00
|
|
|
== How to fix it in Core PHP
|
|
|
|
|
|
|
|
=== Code examples
|
2022-10-24 11:09:58 +02:00
|
|
|
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
|
|
|
|
==== Noncompliant code example
|
|
|
|
|
|
|
|
[source,php,diff-id=1,diff-type=noncompliant]
|
|
|
|
----
|
|
|
|
class AuthenticationHandler {
|
|
|
|
|
|
|
|
public mysqli $conn;
|
|
|
|
|
|
|
|
function authenticate() {
|
|
|
|
$user = $_POST['user'];
|
|
|
|
$pass = $_POST['pass'];
|
|
|
|
$authenticated = false;
|
|
|
|
|
|
|
|
$query = "SELECT * FROM users WHERE user = '" . $user . "' AND pass = '" . $pass . "'";
|
|
|
|
|
2023-03-15 10:55:33 +01:00
|
|
|
$stmt = $this->conn->query($query); // Noncompliant
|
2022-10-24 11:09:58 +02:00
|
|
|
|
|
|
|
if ($stmt->num_rows == 1) {
|
|
|
|
$authenticated = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $authenticated;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
|
|
|
|
[source,php,diff-id=1,diff-type=compliant]
|
|
|
|
----
|
|
|
|
class AuthenticationHandler {
|
|
|
|
|
|
|
|
public mysqli $conn;
|
|
|
|
|
|
|
|
function authenticate() {
|
|
|
|
$user = $_POST['user'];
|
|
|
|
$pass = $_POST['pass'];
|
|
|
|
$authenticated = false;
|
|
|
|
|
|
|
|
$query = "SELECT * FROM users WHERE user = :user AND pass = :pass";
|
|
|
|
|
2023-03-15 10:55:33 +01:00
|
|
|
$stmt = $this->conn->prepare($query);
|
2022-10-24 11:09:58 +02:00
|
|
|
$stmt->bind_param(":user", $user);
|
|
|
|
$stmt->bind_param(":pass", $pass);
|
|
|
|
$stmt->execute();
|
|
|
|
|
|
|
|
$stmt->store_result();
|
|
|
|
|
|
|
|
if ( $stmt->num_rows == 1) {
|
|
|
|
$authenticated = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $authenticated;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
=== How does this work?
|
|
|
|
|
|
|
|
include::../../common/fix/prepared-statements.adoc[]
|
|
|
|
|