How can SQL Injections be prevented in PHP scripts that involve user authentication?
SQL Injections can be prevented in PHP scripts that involve user authentication by using prepared statements with parameterized queries. This method ensures that user input is treated as data rather than executable code, making it impossible for attackers to inject malicious SQL queries.
// Establish connection to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare SQL statement with placeholders
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
// Set parameters and execute
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();
// Check if user exists
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// User authenticated successfully
} else {
// User authentication failed
}
// Close statement and connection
$stmt->close();
$conn->close();