In this post, we will implement a secure login system using PHP’s mysqli
extension with prepared statements. This approach helps prevent SQL injection attacks and enhances the overall security of user authentication. Additionally, we will create session variables to maintain user state after successful login. Error handling and exception handling will be incorporated to ensure robustness.
<?php
session_start(); // Start the session
// Database connection parameters
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';
try {
// Create a new mysqli connection
$mysqli = new mysqli($host, $username, $password, $database);
// Check for connection errors
if ($mysqli->connect_error) {
throw new Exception('Connection failed: ' . $mysqli->connect_error);
}
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Retrieve and sanitize user input
$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
$password = trim($_POST['password']);
// Prepare the SQL statement
$stmt = $mysqli->prepare("SELECT id, password FROM users WHERE email = ?");
if (!$stmt) {
throw new Exception('Prepare failed: ' . $mysqli->error);
}
// Bind parameters
$stmt->bind_param("s", $email);
// Execute the statement
if (!$stmt->execute()) {
throw new Exception('Execute failed: ' . $stmt->error);
}
// Store the result
$stmt->store_result();
// Check if the user exists
if ($stmt->num_rows === 1) {
// Bind the result variables
$stmt->bind_result($userId, $hashedPassword);
$stmt->fetch();
// Verify the password
if (password_verify($password, $hashedPassword)) {
// Password is correct, create session variables
$_SESSION['user_id'] = $userId;
$_SESSION['email'] = $email;
// Redirect to a secure page
header("Location: dashboard.php");
exit();
} else {
echo "Invalid password.";
}
} else {
echo "No user found with that email address.";
}
// Close the statement
$stmt->close();
}
} catch (Exception $e) {
// Handle exceptions
echo 'Error: ' . $e->getMessage();
} finally {
// Close the database connection
$mysqli->close();
}
?>
- Session Management: We start the session to manage user state.
- Database Connection: A connection to the MySQL database is established using
mysqli
. Error handling is implemented to catch connection issues. - User Input Handling: User input is sanitized to prevent XSS attacks.
- Prepared Statements: We use prepared statements to securely query the database, which helps prevent SQL injection.
- Password Verification: The password is verified using
password_verify()
, ensuring that the stored password hash is compared securely. - Session Variables: Upon successful login, session variables are created to maintain user state.
- Error Handling: Comprehensive error handling is included to manage potential issues gracefully.
This code provides a solid foundation for a secure login system in PHP, ensuring both security and user experience are prioritized. This is a perfect foundation to start your next project or enhance your current one.
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
I loved how this article simplified a complex topic! The site’s overall organization makes
finding great articles easy.