What are common pitfalls when using PDO for login scripts in PHP?
Common pitfalls when using PDO for login scripts in PHP include not properly sanitizing user input, not using prepared statements to prevent SQL injection, and not securely storing passwords (such as using plaintext instead of hashing). To solve these issues, make sure to sanitize user input using prepared statements and parameterized queries, and store passwords securely by hashing them before storing in the database.
// Sanitize user input and use prepared statements for login script
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to database
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
// Prepare statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
// Bind parameters
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
// Execute query
$stmt->execute();
// Check if user exists
if($stmt->rowCount() > 0) {
// User authenticated, redirect to dashboard
header("Location: dashboard.php");
} else {
// Invalid login, display error message
echo "Invalid username or password";
}
Related Questions
- What are common challenges faced when handling SOAP responses in PHP?
- How important is the aesthetic aspect of JSON output in PHP, and how does it impact the overall functionality of the code?
- How can one effectively learn PHP programming for game development without relying on others to do the work?