How to implement login/logout in PHP

Updated: January 12, 2024 By: Guest Contributor Post a comment

Overview

When creating web applications, authentication is a common requirement. In this tutorial, we will cover a simple way to implement login and logout functionality using PHP. Beginners and seasoned developers alike will find these fundamental techniques useful for their projects.

Prerequisites:

  • A local development environment for PHP
  • A text editor or IDE (Integrated Development Environment)
  • A web server (such as Apache or Nginx)
  • A database management system (like MySQL)

Setting Up the Database

First, we need to set up a database to store user information. Open your MySQL client and create a new database:

CREATE DATABASE user_db;

USE user_db;

CREATE TABLE users (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(255) NOT NULL
);

Keep in mind that storing plain text passwords is not secure. Always hash passwords before storing them. We will cover this later in the tutorial.

Creating the Login Form

The next step is to create a login form. This form will collect the user’s credentials (username and password):

<form method="post" action="login.php">
    <div>
        <label for="username">Username:</label>
        <input type="text" name="username" required>
    </div>
    <div>
        <label for="password">Password:</label>
        <input type="password" name="password" required>
    </div>
    <div>
        <button type="submit">Login</button>
    </div>
</form>

Next, we handle the form submission in login.php.

Processing the Login Request

Within login.php, start a new session, retrieve the submitted credentials, and verify them against the database:

<?php

session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require 'db_connection.php';

    $username = $_POST['username'];
    $password = $_POST['password'];
    $hashed_password = hash('sha256', $password);

    $query = 'SELECT * FROM users WHERE username = ? AND password = ?';

    if ($stmt = $conn->prepare($query)) {
        $stmt->bind_param('ss', $username, $hashed_password);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $_SESSION['logged_in'] = TRUE;
            $_SESSION['username'] = $username;
            header('Location: user_dashboard.php');
            exit;
        } else {
            echo 'The username or password is incorrect.';
        }
    } else {
        echo 'Database query failed.';
    }
}

?>

The password should be hashed using a salt and proper cryptographic function—PHP’s password_hash() function—when you actually store it in the database. This example uses a simple hash for demonstration purposes.

Creating the Logout Script

Logging out is simply a matter of unsetting session variables and destroying the session:

<?php

session_start();

if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === TRUE) {
    $_SESSION = array();
    session_destroy();
    header('Location: login.php');
    exit;
}

?>

The user is redirected to the login page after logging out.

Bonus Tips

  • Always use HTTPS to prevent credentials from being sent in clear text.
  • Store only hashed passwords in the database using PHP’s password_hash() and password_verify().
  • Implement CSRF (Cross-Site Request Forgery) tokens on login forms to increase security.

Conclusion

In this tutorial, you have learned how to set up a PHP-based login and logout system. To enhance this system’s security, remember to protect against SQL injection by using prepared statements, hash passwords with a proper cryptographic function, and maintain sessions securely. Building on these fundamentals, there are many ways to expand and refine the authentication process to make it more secure and user-friendly.