Login and Logout Using Session in PHP and MySQLi


Login and Logout Using Session in PHP and MySQLi

Hi friends, in this tutorial you will learn how to perform the login and logout using session in PHP and MySQLi or PDO. In order to perform, we need three files with the .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 login 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 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 for Login and Logout Using Session in PHP are mentioned below

Below is a connection file that is used to establish the connection with the MySQL database.

Connect.php:-

<?php
$servername='localhost';
$username="root";
$password="";
try
{
	$con=new PDO("mysql:host=$servername;dbname=blog",$username,$password);
	$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	//echo 'connected';
}
catch(PDOException $e)
{
	echo '<br>'.$e->getMessage();
}
?>

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 the link tag and src attribute of the script tag respectively.

CONCLUSION:- I hope this article will help you to perform the login and log out using session in PHP and MySQLi. If you have any doubt then please leave your comment below.


58 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

    Reply
  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

    Reply
  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!

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

    Reply
  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!

    Reply
  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!

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

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

    Reply
  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!

    Reply
  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

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

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

    Reply
  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!

    Reply
  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!

    Reply
  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!

    Reply
  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!

    Reply
  17. Do you mind if I quote a couple of your posts as long
    as I provide credit and sources back to your site? My blog is in the
    very same area of interest as yours and my users would really benefit from a lot of
    the information you provide here. Please let me know if this okay with you.
    Thank you!

    Reply
  18. Greetings from Colorado! I’m bored to tears at work so I decided to browse
    your site on my iphone during lunch break. I enjoy the knowledge
    you provide here and can’t wait to take a look when I get home.
    I’m shocked at how fast your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyhow, amazing site!

    Reply
  19. An outstanding share! I’ve just forwarded this onto
    a coworker who had been conducting a little research on this.

    And he actually ordered me dinner due to the fact that I found it for him…

    lol. So allow me to reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending some time to talk about this subject here on your internet site.

    Reply
  20. Can I simply say what a comfort to find ann individual who actually understands what they’re talking abvout
    on the net. You actually know how to bring an issue to ligjt
    and make it important. A lot more people should check this out and understand this side of your story.
    I can’t believe yyou are not more popular given that yyou definitely possess the gift.

    Reply
  21. 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 suggestions would be greatly appreciated.

    Reply
  22. Hey just wanted to give you a quick heads up.

    The words in your content seem to be running off the screen in Chrome.
    I’m not sure if this is a format issue or something to
    do with browser compatibility but I thought I’d post to
    let you know. The design look great though! Hope you get the problem solved
    soon. Thanks

    Reply
  23. whoah this weblog is great i like studying your articles.
    Stay up the good work! You realize, lots of individuals are looking round
    for this info, you could aid them greatly.

    Reply
  24. Howdy, i read your blog occasionally and i own a similar one and i was
    just wondering if you get a lot of spam feedback?

    If so how do you reduce it, any plugin or anything you can suggest?
    I get so much lately it’s driving me crazy so any support is very much appreciated.

    Reply
  25. hey there and thank you for your information – I have certainly picked
    up something new from right here. I did however expertise some technical issues using this website, as I experienced to reload the website a lot of times previous to I could get it to load correctly.
    I had been wondering if your hosting is OK? Not that I’m complaining, but slow
    loading instances times will often affect your placement
    in google and can damage your high quality score if ads and marketing with Adwords.
    Anyway I am adding this RSS to my email and can look out for much more of your respective intriguing content.
    Ensure that you update this again very soon.

    Reply
  26. Wonderful website you have here but I was wanting to know if you knew of any forums that
    cover the same topics discussed here? I’d really love
    to be a part of group where I can get comments from
    other experienced people that share the same interest.
    If you have any recommendations, please let me know. Thank you!

    Reply
  27. Pretty section of content. I just stumbled upon your website and in accession capital
    to assert that I get actually enjoyed account your blog posts.
    Anyway I’ll be subscribing to your feeds and even I achievement you access
    consistently quickly.

    Reply
  28. Nice blog here! Also your site loads up very fast! What host are you using?

    Can I get your affiliate link to your host? I wish my web site
    loaded up as quickly as yours lol

    Reply
  29. You really make it appear so easy along with your presentation however
    I find this topic to be actually something that I feel I’d by no means understand.
    It sort of feels too complex and very vast for me.

    I am having a look ahead for your subsequent publish, I’ll attempt to get the hang
    of it! สล็อตเว็บตรง2022

    Reply
  30. Greetings I am so happy I found your blog, I really found you by accident, while I was researching on Aol
    for something else, Anyhow I am here now and would just like to say thanks a lot for a incredible post and a all round interesting blog (I also love the theme/design), I don’t have time
    to read it all at the moment but I have bookmarked it and also included your RSS feeds, so when I have time I will be
    back to read a lot more, Please do keep up the awesome jo.

    Reply
  31. Did you write the article yourself or you hired someone
    to do it? I was wondering because I am a site owner too and struggle with writing new content all the time.
    Someone told me to use AI to do create articles which I am kinda considering because the output is almost written by human. Here is the sample content they sent me – https://sites.google.com/view/best-ai-content-writing-tools/home

    Let me know if you think I should go ahead and use AI.

    Reply
  32. Great site you have here but I was wanting to know if you knew of any forums that cover the same topics discussed in this article? I’d really like to be a part of group where I can get advice from other knowledgeable individuals that share the same interest. If you have any suggestions, please let me know. Many thanks!

    Reply

Leave a Comment