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 login and logout operation, we will take a look briefly about 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 open 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
Session is used with the global variable $_SESSION[”]. We can start the session with the help of session_start() function and we can destroy the session with the help of 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:-
<?php
include '../connect.php';
session_start();
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
//check login details
$stmt = $con->prepare("select * from users where username = '$username' and password = '$password'");
$stmt->execute();
//echo $stmt->rowCount();
//exit();
if($stmt->rowCount()>0){
$_SESSION['username'] = $username;
header("location: home.php");
$_SESSION['success'] = "You are logged in";
}
else{
header("location: login.php");
$_SESSION['error'] = "<div class='alert alert-danger' role='alert'>Oh snap! Invalid login details.</div>";
}
}
?>
<html>
<head>
<title>session example</title>
<link rel="stylesheet" href="../bootstrap.css" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="../bootstrap-theme.css" crossorigin="anonymous">
<style>
.container{
width:50%;
height:30%;
padding:20px;
}
</style>
</head>
<body>
<div class="container">
<h3 align="center"><u>Login Form</u></h3>
<br/><br/><br/><br/>
<?php if(isset($_SESSION['error'])){ echo $_SESSION['error']; }?>
<form action="" method="post" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Username*:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="username" placeholder="Please enter the Username">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="phone">Password*:</label>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" placeholder="Please enter the password">
</div>
</div>
<br/><br/>
<button type="submit" class="btn btn-info btn-block" name="login">Submit</button>
</form>
</div>
<script src="../jquery-3.2.1.min.js"></script>
<script src="../bootstrap.min.js"></script>
</body>
</html>

Home.php:-
<?php
session_start();
include '../connect.php';
if($_SESSION['username']==''){
header("location: login.php");
}
?>
<html>
<head>
<title>ajax example</title>
<link rel="stylesheet" href="../bootstrap.css" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="../bootstrap-theme.css" crossorigin="anonymous">
<style>
.container{
width:50%;
height:30%;
padding:20px;
}
</style>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
<li><a href="#">About US</a></li>
<li><a href="#">Contact US</a></li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<ul class="nav navbar-nav navbar-right">
<a href="logout.php" class="btn btn-danger">Logout</a>
</ul>
</div>
</div>
</nav>
<br/><br/><br/><br/>
<h1 align="center"><?php echo $_SESSION['success']; ?></h1>
<h2 align="center">Welcome to the home page <?php echo $_SESSION['username'];?></h2>
<script src="../jquery-3.2.1.min.js"></script>
<script src="../bootstrap.min.js"></script>
</body>
</html>
Logout.php:-
<?php
include '../connect.php';
session_start();
//destroy the session
session_unset();
//redirect to login page
header("location: login.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 logg in and logg out using session in PHP and MySQLi. If you have any doubt then please leave your comment below.
I constantly spent my half an hour to read this web site’s articles daily along with a cup of coffee.
Fascinating blog! Is your theme custom made or
did you download it from somewhere? A design like yours
with a few simple adjustements would really make my
blog jump out. Please let me know where you got your design. Kudos
Thank you a bunch for sharing this with all folks
you actually recognise what you’re talking approximately!
Bookmarked. Kindly also consult with my
site =). We can have a link change arrangement between us
I constantly spent my half an hour to read this web
site’s posts everyday along with a cup of coffee.
Hi there! This article couldn’t be written much better!
Reading through this article reminds me of my previous roommate!
He always kept talking about this. I’ll forward this information to him.
Pretty sure he’ll have a great read. I appreciate you for sharing!
We are a bunch of volunteers and starting a brand new scheme
in our community. Your website offered us with valuable information to
work on. You have performed a formidable job and our entire community can be thankful to you.
Thanks for your marvelous posting! I actually enjoyed reading it, you happen to be a great
author. I will be sure to bookmark your blog and may come back someday.
I want to encourage you continue your great work, have a nice weekend!
Hey there! I realize this is sort of off-topic however I needed
to ask. Does managing a well-established blog such as yours require a
lot of work? I’m completely new to operating
a blog but I do write in my diary daily. I’d like to start a blog so I can share my own experience and views
online. Please let me know if you have any kind of recommendations or tips for new aspiring bloggers.
Appreciate it!
I have been exploring for a little bit for any high quality articles or blog
posts on this sort of space . Exploring in Yahoo I at last stumbled
upon this website. Reading this info So i’m glad to exhibit that I have
a very just right uncanny feeling I came upon just what I needed.
I so much for sure will make sure to do not overlook this web site and give it a glance on a continuing basis.
Nice respond in return of this matter with solid arguments and describing everything about
that.
Your style is really unique in comparison to other folks I
have read stuff from. Thank you for posting when you’ve got the opportunity, Guess
I will just book mark this site.
I have been surfing online more than three hours as of late,
yet I never discovered any interesting article like yours.
It is beautiful worth enough for me. In my opinion, if all webmasters and bloggers made good content material as you did, the web
will likely be a lot more useful than ever before.
Feel free to surf to my blog post :: 판탄게임
Hello there! This is my first visit to your blog!
We are a group of volunteers and starting a
new initiative in a community in the same niche.
Your blog provided us useful information to work on. You have done
a wonderful job!
Thank you so much
Hi t᧐ every one, because I am really keеn of reading this weblog’s post to be updateԀ on a regular
basis. It carries faѕtidiߋus data.
my web site sarkarinaukri
Thank you so much.
So accelerating the development cycle.Master SAP UI5
/ OpenUI5 Intimately: Standard & State-of-the-art Stages, Bit by bit, With The
assistance of the greatest Open UI5 Professionals.Anubhav UI5 and Fiori Training is the best location to get experienced on SAP UI5
and Fiori Know-how. You could generate a lot of fiori apps over the class, Check out some neat demos here
Hello to every one, the contents existing at this site
are actually awesome for people experience, well,
keep up the nice work fellows.
Nice blog here! Also your site loads up fast! What host are you using?
Can I get your affiliate link to your host? I wish my site
loaded up as fast as yours lol
Hi dear, you can use this link
Interesting blog! Is your theme custom made or did you download it from somewhere?
A design like yours with a few simple tweeks would really make my blog jump out.
Please let me know where you got your theme. Thanks a lot
My theme is free and provided by wordpress
Wonderful, what a blog it is! This blog gives valuable data to us,
keep it up.
Also visit my webpage :: santapan khas Betawi
I have been browsing online greater than three hours nowadays, but I never discovered any fascinating article like yours.
It is lovely price enough for me. Personally, if all web owners and bloggers made just
right content material as you did, the web can be a lot more useful than ever before.
It’s really a great and helpful piece of information. I am happy
that you simply shared this helpful info with us.
Please keep us up to date like this. Thank you for sharing.
Great article! We will be linking to this great post on our site.
Keep up the good writing.
Hi there it’s me, I am also visiting this website
daily, this web page is genuinely nice and the visitors are actually sharing good thoughts.
Wow that was unusual. I just wrote an very long comment
but after I clicked submit my comment didn’t appear.
Grrrr… well I’m not writing all that over again.
Anyway, just wanted to say great blog!
Hmm is anyone else encountering problems with the images on this blog loading?
I’m trying to determine if its a problem on my end or if it’s
the blog. Any feed-back would be greatly appreciated.
You are so interesting! I don’t think I’ve truly read through
a single thing like that before. So nice to find someone with genuine thoughts on this subject.
Really.. thanks for starting this up. This site is something that is
needed on the internet, someone with a little originality!
This article is actually a fastidious one it helps new the web people, who are wishing in favor of blogging.
Terrific post however I was wondering if you could
write a litte more on this topic? I’d be very grateful if you could elaborate a little bit more.
Thank you!
Hey there! This is my 1st comment here so I just
wanted to give a quick shout out and tell you I really enjoy reading your articles.
Can you recommend any other blogs/websites/forums that deal
with the same subjects? Thanks!
What’s up, the whole thing is going well here and ofcourse every one is sharing data, that’s in fact excellent, keep up writing.
Hi there it’s me, I am also visiting this website on a regular
basis, this website is genuinely nice and the visitors are
really sharing pleasant thoughts.
I want to to thank you for this excellent read!!
I certainly enjoyed every bit of it. I have got you bookmarked to check out new things you
post…
Hi there fantastic blog! Does running a blog similar to this take a massive amount work?
I’ve virtually no understanding of coding however I had been hoping to start my own blog soon. Anyway,
if you have any ideas or techniques for new blog owners please share.
I know this is off topic however I just wanted to ask.
Thanks a lot!