What potential security risks are present in the provided PHP code, and how can they be mitigated?
The provided PHP code is vulnerable to SQL injection attacks because it directly concatenates user input into the SQL query. To mitigate this risk, you should use prepared statements with parameterized queries to safely handle user input.
// Original vulnerable code
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Mitigated code using prepared statements
$stmt = $connection->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
Related Questions
- How can the retrieved data from a SQL query be properly displayed in PHP?
- What are the best practices for handling select fields in PHP to ensure that the selected value is retained after editing a record?
- What are the best practices for using Getter/Setter methods to enforce type checking in PHP classes?