User Registration and Login using PHP

What Are We Building?

We’re building a system with the following features:

  1. User Registration: Users can sign up by providing their username, email, and password.
  2. User Login: Users log in using their email and password.
  3. Dashboard: After logging in, users access a personalized dashboard.
  4. Logout: Users can securely log out to end their session.

Setting Up the Environment

Before coding, set up your development environment:

  1. Install XAMPP or WAMP to create a local PHP server.
  2. Open your preferred text editor or IDE (e.g., VS Code).
  3. Create a new project folder called user_system.

Creating the Database

Let’s create the database and table to store user information:

  1. Open phpMyAdmin and create a database called user_system.
  2. Run this SQL command to create the users table:
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

This table will store:

  • username: The user’s name.
  • email: The user’s email (must be unique).
  • password: A hashed version of the user’s password for security.

Connecting to the Database

Create a db.php file to handle the database connection:

<?php
	$host = 'localhost';
	$user = 'root';
	$password = '';
	$dbname = 'user_system'; // Database Name
	
	$conn = mysqli_connect($host, $user, $password, $dbname);

	if (!$conn) {
    	die('Database connection failed: ' . mysqli_error());
	}
?>

This file ensures that PHP connects to the database. Any issues? The error message will help debug.


User Registration (register.php)

This page allows new users to register by providing their username, email, and password. It checks if the email already exists in the database and if not, it inserts the new user into the database.

Registration Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
</head>
<body>
    <h2>Register</h2>
    <form action="register.php" method="POST">
        <label for="username">Username:</label>
        <input type="text" name="username" required><br>

        <label for="email">Email:</label>
        <input type="email" name="email" required><br>

        <label for="password">Password:</label>
        <input type="password" name="password" required><br>

        <button type="submit" name="register">Register</button>
    </form>

    <p>Already have an account? <a href="login.php">Login here</a></p>
</body>
</html>
  • The form submits a POST request to the same page (register.php).
  • The form collects username, email, and password from the user.
  • Error or success messages are shown based on the PHP logic processed above..

PHP Registration Logic

In register.php, we’ll check if the form has been submitted and insert the data into the database.

<?php
include 'includes/db.php';

if (isset($_POST['register'])) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    // Hash the password before storing
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Use raw SQL query (not prepared statements)
    $sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$hashed_password')";

    if (mysqli_query($conn, $sql) === TRUE) {
        echo "Registration successful! <a href='login.php'>Login here</a>";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
    
    // Close database connection
    mysql_close($conn);
}
?>

Database Connection:

  • include 'includes/db.php'; includes the database connection file. This ensures the $conn variable, which connects to the database, is available in this file.

Form Handling:

  • The if (isset($_POST['register'])) block checks if the form was submitted (i.e., the user clicked the Register button).
  • The $_POST variables $_POST['username'], $_POST['email'], and $_POST['password'] fetch the user input from the registration form.

Password Hashing:

  • Passwords should never be stored in plain text. The line $hashed_password = password_hash($password, PASSWORD_DEFAULT); hashes the password using PHP’s password_hash() function. This converts the plain-text password into a secure hash that will be stored in the database.

Email Check:

  • A query (SELECT * FROM users WHERE email = '$email') is run to check if the email is already registered in the database.
  • If a user with the same email already exists, an error message is displayed.

User Registration:

  • If the email does not exist, a query (INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$hashed_password')) inserts the new user into the users table with the provided username, email, and hashed password.

Error and Success Handling:

  • If the registration is successful, a success message is displayed. If there’s an error with the query or email duplication, an error message is shown.

User Login (login.php)

This page handles the login process. The user enters their email and password, and the system checks the credentials.

If they are correct, the user is logged in and redirected to the dashboard.

Login Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>

    <!-- Display error messages -->
    <?php if ($error_message): ?>
        <p style="color: red;"><?php echo $error_message; ?></p>
    <?php endif; ?>

    <!-- Login form -->
    <form action="login.php" method="POST">
        <label for="email">Email:</label>
        <input type="email" name="email" required><br>

        <label for="password">Password:</label>
        <input type="password" name="password" required><br>

        <button type="submit" name="login">Login</button>
    </form>

    <p>Don't have an account? <a href="register.php">Register here</a></p>
</body>
</html>
  • Similar to the registration page, the form submits a POST request to the login.php page.
  • The form collects email and password from the user and sends them for validation.
  • If there’s an error (invalid email or password), an error message is shown.

PHP Code Block - Login Logic

<?php
include 'includes/db.php'; // Connect to the database
session_start(); // Start the session to store user data
$error_message = ''; // Initialize error message

// Handle login when the form is submitted
if (isset($_POST['login'])) {
    $email = $_POST['email']; // Get the email from the form input
    $password = $_POST['password']; // Get the password from the form input

    // Query to fetch the user with the given email
    $login_query = "SELECT id, username, password FROM users WHERE email = '$email'";
    $result = mysqli_query($conn, $login_query);
    
    // Check if user exists
    if (mysqli_num_rows($result) > 0) {
        $user = mysqli_fetch_assoc($result); // Fetch user data
        
        // Verify the password using password_verify()
        if (password_verify($password, $user['password'])) {
            // Password is correct, start a session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];

            // Redirect to the dashboard after successful login
            header("Location: dashboard.php");
            exit;
        } else {
            $error_message = "Invalid password!";
        }
    } else {
        $error_message = "No user found with that email!";
    }
    
    // Close database connection
    mysql_close($conn);
}
?>

Session Handling:

  • The session_start() function starts the session to store user data (such as their user_id and username) after login.

Form Handling:

  • Similar to the registration page, the isset($_POST['login']) checks if the form is submitted.
  • The $_POST['email'] and $_POST['password'] fetch the login credentials from the form.

Email Lookup:

  • The query SELECT id, username, password FROM users WHERE email = '$email' checks if the user exists by their email.

Password Verification:

  • password_verify() compares the plain-text password with the hashed password stored in the database.
  • If they match, the user is successfully logged in and their session is initialized.

Redirection:

  • Upon successful login, the user is redirected to the dashboard.php page. If the credentials are incorrect, an error message is displayed.

Dashboard (dashboard.php)

The dashboard.php page serves as the landing page or the homepage after the user logs in.

It shows a welcome message and provides access to user-specific content. It's a protected page, meaning only authenticated (logged-in) users can access it.

<?php
	session_start();
	// If no user is logged in, redirect to login page
	if (!isset($_SESSION['user_id'])) {
    	header("Location: login.php");
    	exit;
	}

	echo "Welcome, " . $_SESSION['username'] . "!<br>";
	echo "<a href='logout.php'>Logout</a>";
?>

session_start():

  • The session_start() function is called to access the session variables that store the logged-in user’s data (like $_SESSION['user_id'] and $_SESSION['username']).

Checking if User is Logged In:

  • The conditional if (!isset($_SESSION['user_id'])) checks if the user’s user_id is set in the session.
  • If the session variable $_SESSION['user_id'] is not set, it means the user is not logged in, so the user is redirected to the login page (header("Location: login.php");).
  • The exit; ensures that the script stops execution immediately after the redirect.

Displaying the Dashboard:

  • If the user is logged in, the dashboard content is displayed. The welcome message shows the logged-in user's username ($_SESSION['username']).

Logout Link:

  • There is a link provided to log the user out. When clicked, this will redirect the user to logout.php, where the session will be destroyed, and they will be logged out.

Logout (logout.php)

The purpose of logout.php is to log out the user by clearing their session and redirecting them back to the login page.

This ensures that the user’s session is terminated, and they need to log in again to access the protected pages.

<?php
	session_start();
	session_unset(); // Unset all session variables
	session_destroy(); // Destroy the session
	
	header("Location: login.php"); // Redirect to login page
	exit;
?>

session_start():

  • This function is called at the beginning of the script to ensure that the session is started and we can access the session variables. It allows us to manage and manipulate session data (like user information).

session_unset():

  • This function removes all session variables. It essentially "unsets" the session data, which is the data stored about the user in the session (like $_SESSION['user_id'], $_SESSION['username']).

session_destroy():

  • After unsetting the session variables, this function destroys the session entirely, which means the session ID is no longer valid. This ensures the user is fully logged out.

header("Location: login.php"):

  • This redirects the user back to the login page after they have been logged out. The exit; is used to terminate the script immediately, ensuring no further code is executed after the redirection.