Login and Logout Using Session in PHP and MySQLi

Bipsmedium
2 min readMay 12, 2020

--

How to create login and logout using session in PHP and MySQLi

Now, we are going to perform the login and logout using session in PHP and MySQLi In order to perform, we need three files with .php extension.

1. login.php
2. home.php
3. logout.php

Here, we will not be doing registration for the users because I have covered this earlier. For the registration part, you can check How to insert HTML form data in MySQL database using PHP

Put these three files in a folder name session.

Before getting started with the login and logout operation, we will take a look briefly at the session.

Basic overview of the session in PHP | What is the session in PHP

A session is just a time duration of a user for the activities he performs on the web. For eg:-when a user opens Facebook and log in to view his Facebook profile and after completing the activities he logout. The time between login and log out is called a session.

How to use session in PHP

A session is used with the global variable $_SESSION[‘’]. We can start the session with the help of the session_start() function and we can destroy the session with the help of the session_unset() function.

Here, we will use a table named ‘users’

DDL information of the table:-

CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(225) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`phone_no` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(225) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`password` varchar(225) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

In this tutorial, we will assume that we already have a username and password because the registration part of the user has already been done. On the other hand, you can also enter a username and password directly in the table into the database just for testing purposes.

Now, if the login details are correct then we will redirect to the home page with the welcome message otherwise we will redirect to the login page again showing the invalid login details.

Required files are mentioned below:-

Login.php

Home.php

Logout.php

NOTE*
— — — —
Download the bootstrap CSS and js files from google and include the path of the files in the href attribute of link tag and src attribute of the script tag respectively.

CONCLUSION:- I hope this article will help you to perform the login and logout using a session in PHP and MySQLi.

--

--

Bipsmedium

Hi, This is Biplab and I am a PHP laravel developer and other open source technologies. I am here to share my experience with the community.