blog

Home / DeveloperSection / Blogs / Login and Logout in PHP

Login and Logout in PHP

Mark Devid 6019 24-Jun-2016

In previous article we have discussed about the registration form today we will learn about how to login and logout in PHP.

Sometimes beginners get confused how to login and logout. So I thought it would be helpful if I share some basic steps how to create login and logout with session.

Followings are the topics which we will learn in this part of section:

  •   Login form using PHP
  •    Validation and session in login form
  •    Logout with session

Step1: Login form using PHP

In your login form it is necessary to give form tag which should have method “post” (please note you should not give get method in your form tag) and action attribute which will submit your processing page or as I do it in current page. Please note session_start() is written to create a session which we will discuss later in this part. Following is form.php page:

Code Implementation:

<?php
session_start()
?>
<style>
.login
{
    width:30%;
          height:40%;
    background-color: lightgrey;
}
.log
{
          height:25px;
          width:200px;
          }
          .user1
          {
           margin-top:80px;
           }
.text
{
   margin-top:30px;
   width:90px;
   height:30px;
           }
input[type=text],input[type=password]
 {
    padding: 16px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    border-radius: 6px;
    box-sizing: border-box;
}
input[type=submit]
{
    background-color: #4CAF50;
    color: white;
    padding: 10px 10px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
input[type=submit]:hover
{
    background-color: lightblue;
}
</style>
<center>
<form method="post">
<div class="login">
<table>
<tr><td>Username:</td><td><input type="text" placeholder="USERNAME" name="uname" class="log" /></br></td></tr> <tr><td>Password:</td><td><input type="password" placeholder="PASSWORD" name="pass" class="log" required/></td></tr></br> <tr><td></td><td><input type="submit" value="Submit" name="submit" class="text"></td></br> </div>
</form>
</center>

As from the above code you can see that a form is made which has “post” method and also has two fields: first is the username which has a name attribute “uname” and second is the password which has a name attribute “pass” and the last is a submit button. Rest code is the styling code which you can give your own as you fit. Following is an output of the form:

Login and Logout in PHP

Please note you can give your own style as you want to give.

Step2: Validation and session in login Form

Now we are having a form which is submitting username and password. Now we will apply some validation on both username and password. It will check whether the username is entered or password is entered or not. It will also check whether username is in the database or not then create an account. If successful, then send the user to its profile and if not send back to the login page. Following is a code for validation and session:

<?php

if(isset($_POST["submit"]))
{ $uname=$_POST["uname"];
          $pass=$_POST["pass"];
          require_once("connect.php");
      if(empty($uname) && empty($pass))
   {
     echo(" <h3 class='text'> Please enter your username and password </h3>");
   }
           else
           {
              if(empty($uname))
      {
          echo(" <h3 class='text'> Please enter your username </h3>");
      }
        if(empty($pass))
      {
          echo(" <h3 class='text'> Please enter your password </h3>");
      }
           }
    if(!empty($uname) && !empty($pass))
         {
              $res = $con->query("select * from user_login where username='$uname' and password ='$pass'");                      if($res->num_rows>0) // It will check whether any data exists or not                      {
                      $re=$res->fetch_assoc();
                        $_SESSION["username"]=$re["username"];
                              $_SESSION['isLogin']=true;
                               echo($re["username"]);
                        header("location: home.php");
                              die(0);
                     }
           else
              {
                 echo("Incorrect Username or password");  
                    }
                               }

}  
?>

 Now let’s understand the code: isset($_POST[“submit”]) means when you have clicked on submit button then only further process will run or execute, require_once(“connect.php”) will include the file.

Now comes validation part where empty($uname) && empty($pass) means username and password field is empty then it will validate and return message “Please enter your username and password” (see image 1)same will work for empty($uname)(see image 2) and empty($pass)(see image 3). After that when you have entered the username and password it will check whether username exists in database or not and if not then it will give the message “incorrect username or password” (see image 4) and if both are correct then session will send you to you profile. Please note if you don’t have any knowledge about validation please visit our previous page of validation.

Login and Logout in PHP

When you have successfully entered your username and password then you will enter your own profile. This will be done by creating one login.php page which will have above code:  

<?php
session_start();
if($_SESSION['isLogin']!=true)
{
header("Location:login.php");
die(0);}
?>
<h1> Welcome,<?=$_SESSION["username"]?> </h1>
<a href="logout.php" class="logout">Logout</a>
<style>
.logout
{
float:right
}
</style>

 From the above code you can see if $_SESSION[‘isLogin’]!= true then it will redirect to login.php page else if it is true then it will open your account.

Step 3: Logout using session

Now to logout we use session_destroy() to logout the page. Following is a logout.php page:

<?php
  session_start(); // start the session
session_destroy(); // delete the session
 header('Location: login.php');
?>

  

As from the above code you can see that session is destroyed and after destroying session it will redirect to login.php page.

In this part we have made three pages: first for the form.php, second is the profile.php where user profile will be shown and third is the logout.php. Below is the merge code for all form.php pages where you can copy and run the program easily.

Form.php
<?php
session_start()
?>
<style>
.login
{
    width:40%;
          height:40%;
    background-color:lightgrey;
}
.log
{
    margin-top:30px;
          height:25px;
          width:220px;
          }
          .user1          {
           margin-top:80px;
           }
.text
{
   margin-top:30px;
   width:90px;
   height:30px;
           }
</style>
<center>
<form method="post" class="user1" onsubmit="return validate()">
<div class="login">
<h2><u>User LogIn</u></h2>
USERNAME:<input type="text" placeholder="USERNAME" name="uname" class="log" /></br> PASSWORD:<input type="password" placeholder="PASSWORD" name="pass" class="log" requitred></br> <input type="submit" value="submit" name="submit" class="text"></br> <a href="userlogin.php" style="margin-left:-200px">Create an account</a> </div>
</form>
</center>
<?php
if(isset($_POST["submit"]))
{ $uname=$_POST["uname"];
          $pass=$_POST["pass"];
          require_once("connect.php");
      if(empty($uname) && empty($pass))
   {
     echo(" <h3 class='text'> Please enter your username and password </h3>");    }
           else
           {
              if(empty($uname))
      {
          echo(" <h3 class='text'> Please enter your username </h3>");
      }        if(empty($pass))
      {
          echo(" <h3 class='text'> Please enter your password </h3>");
      }
           }
    if(!empty($uname) && !empty($pass))
         {
                    $pass=md5($pass);
              $res = $con->query("select * from user_login where username='$uname' and password ='$pass'");                      if($res->num_rows>0)
                     {
                      $re=$res->fetch_assoc();                         $_SESSION["username"]=$re["username"];
                              $_SESSION['isLogin']=true;
                               echo($re["username"]);
                      header("location: home.php");
                              die(0);
                     }
           else
              {
                 echo("Incorrect Username or password");
                  }

                               }

}
?>

Updated 16-Mar-2018

Leave Comment

Comments

Liked By