What potential security risks are present in the code snippet provided, and how can they be mitigated?
The code snippet provided is vulnerable to SQL injection attacks due to directly interpolating 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 snippet
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
// Mitigated code snippet using prepared statements
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();
Related Questions
- How can you replicate the functionality of PHP's shuffle() function using only basic loops and if statements, without using array functions like array_values or in_array?
- How can the order of variable assignment affect the content transferred in emails in PHP?
- What are the potential pitfalls of treating postal codes as strings in PHP when implementing a form for user input?