What potential security risks are present in the PHP code provided for the login functionality?
The potential security risks present in the PHP code for the login functionality include vulnerability to SQL injection attacks due to the use of unsanitized user input in the SQL query. To solve this issue, we should use prepared statements with parameterized queries to prevent SQL injection attacks.
// Original vulnerable code
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);
// Fixed code using prepared statements
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username=? AND password=?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
Related Questions
- What are some best practices for beginners to follow when using PHP functions for date manipulation?
- What are common pitfalls to avoid when using error_reporting() in PHP for error handling in complex web applications?
- What potential issue is the user facing with connecting to the SQL Server in their PHP code?