PHP MySQL Creating a login form
Creating a login form using PHP MySQL in procedural style involves collecting user credentials (email/username and password), validating them, checking if they match the records in the database, and then logging the user in. We'll also use password_verify()
to compare the plain-text password with the hashed password stored in the database.
Steps:
- Create a login form (HTML).
- Handle the form submission in PHP.
- Validate and sanitize user input.
- Retrieve user details from the database.
- Verify the password.
- Provide feedback (success or error messages).
Example: Login Form with PHP MySQL
Step 1: HTML Form for User Login
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Login</title>
</head>
<body>
<h2>User Login</h2>
<form action="login.php" method="POST">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Step 2: PHP Code to Handle Login (login.php
)
This PHP script processes the login form and checks the credentials against the database.
<?php
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Step 1: Capture and sanitize the input data
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// Sanitize input
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Step 2: Validate input
if (empty($email) || empty($password)) {
die("Both fields are required.");
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format.");
}
// Step 3: Establish a MySQL connection
$servername = "localhost";
$db_username = "root";
$db_password = "";
$dbname = "test_db";
// Create connection
$conn = mysqli_connect($servername, $db_username, $db_password, $dbname);
// Check if connection was successful
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Step 4: Retrieve the user data based on the email
$sql = "SELECT * FROM users WHERE email = ?";
$stmt = mysqli_prepare($conn, $sql);
// Bind parameters
mysqli_stmt_bind_param($stmt, "s", $email);
// Execute query
mysqli_stmt_execute($stmt);
// Get the result
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) == 1) {
// Fetch the user data
$user = mysqli_fetch_assoc($result);
$hashed_password = $user['password'];
// Step 5: Verify the entered password with the hashed password
if (password_verify($password, $hashed_password)) {
// Start a session or redirect the user to a protected page
session_start();
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
echo "Login successful! Welcome " . $_SESSION['username'];
// Redirect to a protected page (e.g., dashboard.php)
// header("Location: dashboard.php");
} else {
echo "Invalid password.";
}
} else {
echo "No user found with that email.";
}
// Step 6: Close the connection
mysqli_close($conn);
}
?>
Step-by-Step Explanation:
Sanitize and Validate Input:
- The
$_POST
data is sanitized usingfilter_var()
to remove illegal characters from the email and password. - The email is validated to ensure it's in the correct format.
- The
Connect to the MySQL Database:
- The script establishes a connection to the MySQL database using
mysqli_connect()
.
- The script establishes a connection to the MySQL database using
Retrieve User Data:
- A prepared statement is used to retrieve the user data based on the provided email. This prevents SQL injection.
- The
mysqli_stmt_bind_param()
function binds the email parameter to the prepared SQL query. - The query result is fetched using
mysqli_stmt_get_result()
.
Verify Password:
- The
password_verify()
function compares the plain-text password entered by the user with the hashed password retrieved from the database. - If the password matches, the user is logged in and a session is started.
- The
Session Handling:
- Upon successful login, a session is started using
session_start()
. - User information, such as the
user_id
andusername
, is stored in the session to manage user state across different pages.
- Upon successful login, a session is started using
Provide Feedback:
- If the login is successful, the user is redirected to a protected page or shown a success message.
- If the email or password is incorrect, error messages are displayed.
Step 3: Create the Database Table
Make sure you have a users
table in your MySQL database to store user information like the hashed password, email, and username.
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE users (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Verifying Login with password_verify()
The password_verify()
function is crucial for securely comparing the entered password with the stored hashed password. If the passwords match, the user is successfully logged in.
Key Security Measures:
Prepared Statements:
- Using
mysqli_prepare()
andmysqli_stmt_bind_param()
ensures that your queries are protected against SQL injection attacks.
- Using
Password Hashing:
password_verify()
allows you to securely compare the plain-text password with the hashed password stored in the database.- Passwords should never be stored in plain text. Always hash passwords before storing them.
Session Management:
- When the user successfully logs in, start a session using
session_start()
. Store relevant session variables likeuser_id
orusername
to manage the user session. - For security, ensure your session is properly managed and secure by using
session_regenerate_id()
after login and setting proper session configurations.
- When the user successfully logs in, start a session using
Conclusion:
This example demonstrates how to create a secure login system using PHP and MySQL in procedural style. The key security features are:
- Password hashing and verification with
password_verify()
. - Prepared statements to prevent SQL injection.
- Session management to handle logged-in users.