Sling Academy
Home/PHP/How to implement login/logout in PHP

How to implement login/logout in PHP

Last updated: January 12, 2024

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.

Next Article: How to Redirect to Another Page in PHP

Previous Article: How to use sessions in PHP

Series: Building Dynamic Web Pages with PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array