---
title: "Login and Logout in PHP"  
description: "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"  
author: "Mark Devid"  
published: 2016-06-24  
updated: 2018-03-16  
canonical: https://www.mindstick.com/blog/11166/login-and-logout-in-php  
category: "php"  
tags: ["php"]  
reading_time: 8 minutes  

---

# Login and Logout in PHP

In previous article we have discussed about the [registration form](https://www.mindstick.com/Articles/12165/registration-in-php) 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](https://www.mindstick.com/articles/12852/styles-login-form-in-android) using PHP

- [Validation](https://www.mindstick.com/articles/12234/validation-using-data-annotation-using-entity-framework) 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](https://www.mindstick.com/blog/221/attributes-reflection) which will submit your [processing](https://www.mindstick.com/blog/254/background-processing-in-android) 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](https://www.mindstick.com/forum/33764/how-to-implementation-of-class-in-c-sharp):**

```
<?phpsession_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](https://www.mindstick.com/forum/130/its-possible-without-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](https://www.mindstick.com/blogs/5b336dcc-698a-4bbd-a8df-cb1fd86b7015/images/34197495-6fc7-46f8-9bf1-28613af4f0be.png)\

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](https://www.mindstick.com/blogs/5b336dcc-698a-4bbd-a8df-cb1fd86b7015/images/8e36b1d9-3566-4b7f-a255-496ddfbc800a.png)\

When you have successfully entered your [username and password](https://www.mindstick.com/forum/160407/how-does-a-bearer-token-differ-from-other-authentication-methods-such-as-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:

```
<?phpsession_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](https://answers.mindstick.com/qa/93286/what-are-the-benefits-after-upgrading-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 sessionsession_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](https://www.mindstick.com/forum/160226/how-to-extend-the-default-user-profile-information-in-asp-dot-net-core-identity) 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

#####

```
<?phpsession_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><?phpif(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");
                   }
                               }

}
?>
```

---

Original Source: https://www.mindstick.com/blog/11166/login-and-logout-in-php

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
