Building a website in php html and CSS with login and logout functions. Do not worry, its super easy. Just you need to get little understanding of php sessions.
Sessions are kind of state maintained by the server that stores esseential user data to identify a specific user at any particular instance of time.
In PHP, we start a session on successful login, store username and essential user data on different session variables and destroy the session on logout.
Recommended read,
See full php login code using sessions
That is, when user successfully logs in, declare some session variables as many as you need and store essential user data on it. These variables will be needed during navigation across pages to identify the specific user.
Sessions are kind of variables which stores essential user data and can be accessed across all the php pages in a website. Only thing you need is start a session on every page.
Steps for login-logout
- Create session variable on successful login
- Check whether session variable is set or not in home page, if not set redirect to login page
- Destroy the session variable on logout
Code for home page using session
Use this code in your home page. What this code does is, it uses isset() function that checks for the session variable whether it is set or not. If the variable is not set, redirect the user to login page.
<?php session_start(); if(!isset($_SESSION['username'])){ header('location: login.php'); } ?>
Code for Logout page using session
Use the below code in logout page. First a start a session to access the session variable. Use the isset() function to check the session variable set or not. Destroy the session if session varibale found to be set and redirect the user to login page.
<?php session_start(); if(isset($_SESSION['username'])){ session_destroy(); header('location: login.php'); } else{ header('location: index.php'); } ?>
Published on July 3, 2021