Skip to content
PHP Logo

What potential security risks are present in the provided login.php script?

The provided login.php script is vulnerable to SQL injection attacks as it directly concatenates user input into the SQL query. To solve this issue, you should use prepared statements with parameterized queries to prevent SQL injection. Additionally, it's recommended to hash the passwords before storing them in the database for added security.

php
// Fix for login.php script to prevent SQL injection

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');

// Bind the parameters
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);

// Execute the query
$stmt->execute();

// Fetch the user data
$user = $stmt->fetch();

// Check if user exists and password is correct
if ($user && password_verify($_POST['password'], $user['password'])) {
    // User authenticated, proceed with login
} else {
    // Invalid credentials
}