Log In or Log Out Registered Users using php

Ghulam Mujtaba - Jul 8 - - Dev Community

In our previous project, we learned how to register a new account on a website by providing an email and password. However, we stored the password in the database in plain text, which is not secure. Now, we will learn how to hash the password using BCRYPT before storing it in the database.

$db->query('INSERT INTO users(email, password) VALUES(:email, :password)',[
    'email' => $email,
    'password' => password_hash($password, PASSWORD_BCRYPT)
]);
Enter fullscreen mode Exit fullscreen mode

This code hashes the password using BCRYPT and stores it in the database.

Intro to BCRYPT

BCRYPT is a password hashing algorithm that secures passwords by transforming them into a hashed format. This makes it difficult for attackers to access the original password.

Login System

Now that we have hashed passwords in our database, we need to create a login system that allows users to log in with their email and password.

Login Page

To create a login page, we need to add a route and a controller to handle the login process.

$router->get('/login', 'controllers/session/create.php')->only('guest');
Enter fullscreen mode Exit fullscreen mode

This route maps the URL /login to the create.php controller in the session directory, and only allows guest users to access it.

<?php view('session/create.view.php');
Enter fullscreen mode Exit fullscreen mode

This controller renders the create.view.php view, which contains the login form.

Login Form

To create login form go to registration/create.view.php. Open it and copy all code and paste it in new created file.
The login form contains fields for email and password , in this code we need to update headings and text for button.

<button type="submit" 
        class="group relative flex w-full justify-center rounded-md border border-transparent bg-indigo-600 py-2 px-4 text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2" 
        > 
    Log In 
</button>
Enter fullscreen mode Exit fullscreen mode

This code creates a submit button for the login form.

Login Function

As the login form is created then we have to add and declare login function. The login function is used to verify the user's credentials and log them in.

function login($user) {
    $_SESSION['user'] = [
        'email' => $user['email']
    ];
    session_regenerate_id(true);
}
Enter fullscreen mode Exit fullscreen mode

A user can login by inputting any email or password, as there is no strict rule to follow for logging into the system. Therefore, we must verify credentials to ensure that only authorized users can access the system.

Verifying Credentials

To verify credentials, we'll implement strict rules to check as the email and password match the records in our database before allowing access to the system.
Steps to verify credentials:

  • Verify the email and password by querying the database.
  • Use password_verify() to check if the input password matches the hashed password in the database.
  • If the email and password are correct, log in the user.
$user = $db->query('select * from users where email = :email', [
    'email' => $email
])->find();

if ($user) {
    if (password_verify($password, $user['password'])) {
        login([
            'email' => $email
        ]);
        header('location: /');
        exit();
    }
}
Enter fullscreen mode Exit fullscreen mode

This code queries the database for a user with the given email, and then uses password_verify() to check the password. If the password is correct, the user is logged in and redirected to the home page.

Logout Function

As a user is logged into the system then we have to implement logout functionality, we define a route that maps the URL /session to a controller that destroys the session.

$router->delete('/session', 'controllers/session/destroy.php')->only('auth');
Enter fullscreen mode Exit fullscreen mode

Then we have to add a controller for deleting session by calling log out function in this.

<?php

logout();

header('location: /'); 
exit();
Enter fullscreen mode Exit fullscreen mode

The logout function is used to destroy the session and log the user out.

function logout() {
    $_SESSION = [];
    session_destroy();
    $params = session_get_cookie_params();
    setcookie('PHPSESSID', '', time() - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
Enter fullscreen mode Exit fullscreen mode

This function destroys the session. $params is used in PHP to make cookies more secure. The $params array contains settings that can help secure cookies, such as:

  • Secure flag ($params['secure']): Forces the cookie to be transmitted over a secure connection (HTTPS).
  • Domain and path settings ($params['domain'] and $params['path']): Control where the cookie is valid.

By using $params to set these settings, we can make our cookies more secure and reduce the risk of attacks.

Access Control

To restrict access to certain pages, we can add conditions to check if the user is logged in means only authenticated user an see the notes.

<?php if ($_SESSION['user'] ?? false) : ?>
    <a href="/notes" 
       class="<?= urlIs('/notes') ? 'bg-gray-900 text-white' : 'text-gray-300' ?> hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium">Notes</a>
<?php endif ?>
Enter fullscreen mode Exit fullscreen mode

This code checks if the user is logged in, and if so, displays a link to the notes page.

Logout Button

The logout button is only visible to logged-in users. When clicked, it submits a form to the /session route with a hidden field to log out the user from the system.

<div class="ml-3>
  <form method="POST" action="/session">
                                <input type="hidden" name="_method" value="DELETE"<button class="text-white">Log Out</button>
                            </form>
  </div>
 <?php else : ?>
     <div class="ml-3">
  <a href="/registration class="<?= urlIs('/register') ? 'bg-gray-900 text-white' : 'text-gray-300' ?> hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium">Register</a>
 <a href="/login" class="<?= urlIs('/login') ? 'bg-gray-900 text-white' : 'text-gray-300' ?> hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium">Log
                                In</a>
      </div>
        <?php endif ?>


Enter fullscreen mode Exit fullscreen mode

I hope that you have clearly understood how to login or logout user.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player