Dj Techblog

A blog on web development

Login-logout using php sessions

Last modified on July 3, 2021
Login-logout using php sessions

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

  1. Create session variable on successful login
  2. Check whether session variable is set or not in home page, if not set redirect to login page
  3. 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


Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.