In this post, we will implement a secure login system using PHP 8 and PDO (PHP Data Objects). This approach ensures that user credentials are handled safely, protecting against SQL injection attacks and enhancing overall security. We will create a simple login form, validate user input, and authenticate users against a database.
<?php
// Database configuration
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// Login logic
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
// Prepare and execute the SQL statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?');
$stmt->execute([$username]);
$user = $stmt->fetch();
// Verify password
if ($user && password_verify($password, $user['password'])) {
// Start session and set user data
session_start();
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
echo 'Login successful!';
} else {
echo 'Invalid username or password.';
}
}
?>
<!-- HTML Form -->
<form method="POST" action="">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
In the code above, we first establish a connection to the database using PDO. This is done by specifying the database host, name, user, password, and character set. The connection is wrapped in a try-catch block to handle any potential exceptions that may arise during the connection process.
Next, we check if the request method is POST, indicating that the login form has been submitted. We retrieve the username and password from the form input.
To prevent SQL injection, we use prepared statements. The SQL query selects a user from the users
table based on the provided username. The execute
method is called with an array containing the username, which safely binds the parameter.
Once we have the user data, we verify the password using the password_verify
function. This function checks the provided password against the hashed password stored in the database. If the credentials are valid, we start a session and store the user ID and username in session variables, indicating a successful login.
If the credentials are invalid, an error message is displayed to the user.
This implementation not only secures user authentication but also adheres to best practices in PHP development, ensuring a robust and secure login system.
Happy coding… 🙂
I’ve been designing web applications—on and off—since 2001, back when animated GIFs were all the rage and ‘responsive design’ meant answering your client’s emails. Over the past 14 years, I’ve kept pace with the ever-evolving trends in PHP development, successfully delivering a variety of projects that made my clients happy (and kept me caffeinated).
This website serves as my soapbox—a place to share the insights I’ve picked up along the way with anyone curious enough to dive in. Welcome aboard!
Need some custom work done? Or, just want to reach out? Email: dan@danoriordan.com