Login and Logout Using Session in PHP and MySQLi


 

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 and Logout Using Session in PHP and MySQLi

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.


37 thoughts on “Login and Logout Using Session in PHP and MySQLi

  1. 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

  2. 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

  3. 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!

  4. 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.

  5. 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!

  6. 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!

  7. 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.

  8. 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 :: 판탄게임

  9. 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!

  10. 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

  11. 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.

  12. 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.

  13. 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!

  14. 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!

  15. 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!

  16. 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!

Leave a Reply

Your email address will not be published.

Theme of 96 THEME.