I know as a PHP beginner, Session and Cookies are one of the confusing topics. Because both stores user data. But the differences in both of them are session stored user data in server while cookies store user data in the user browser. Session data is only available for the current session while cookie can be stored for a longer period of time.
In this tutorial I am not going to cover cookies but I will cover PHP Session using login and logout example. Let’s have a look on what session do.
- Session makes user data available across the whole website.
- Session makes a temporary file in a server temporary directory which saves session data. Temporary file path is saved in php.ini file.
- Sessions atomically destroys when user close the browser.
- Session will start by calling
session_start()
function. - Session will destroy by calling
session_destroy()
function.
Session in PHP example for login and logout
I am going to create one HTML Login form with email and password fields. When user will submit the form, first I will check that both fields must have values then I will check user email exist or not. if email will exist then I will confirm user password. Password will be checked by password_verify
function. If you don’t know how password_verify
function works, then please read my post how to use PHP password_hash in registration and login form for better understanding.
If user adds correct email and password then will create session and send user to dashboard.php
. In dashboard.php
page there will be logout button. By clicking on logout user will easily logout and will redirect to index.php
page. Not let’s start.
Create Database:
1 2 3 |
Create database demo; |
Create Database Table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE TABLE `users` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(255) NULL DEFAULT NULL, `last_name` VARCHAR(255) NULL DEFAULT NULL, `email` VARCHAR(255) NULL DEFAULT NULL, `phone` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NULL DEFAULT NULL, `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=7 ; |
Create Database Configuration file: (config.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $host = 'localhost'; $DBUser = "root"; $DBPassword = ''; $db = 'demo'; $conn = mysqli_connect($host,$DBUser, $DBPassword, $db); if(!$conn) { die(mysqli_error()); } ?> |
This is a beginner tutorial so I am using mysqli_connect()
function to connect to the database.
HTML Login Form: (index.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<div class="container"> <h1>PHP Login and Logout with Session</h1> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <div class="field-container"> <label>Email</label> <input type="email" name="email" required placeholder="Enter Your Email"> </div> <div class="field-container"> <label>Password</label> <input type="password" name="password" required placeholder="Enter Your Password"> </div> <div class="field-container"> <button type="submit" name="submit">Submit</button> </div> </form> </div> |
As you can see in the above html code. There is just a container div under which form code is written. Form action has $_SERVER['PHP_SELF']
which means form will be submitted on the same page.
Style.css:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
body{ font-family:verdana; background-color:#aaaae3; } .container{ width:40%; margin:10% auto; border:1px solid #eeeeee; background:#ffffff; } .container-dashboard{ width:90%; border:1px solid #eeeeee; background:#ffffff; padding:10px; } .field-container{ margin:10px auto; width:400px; } h1{ text-align:center; line-height:30px; font-size:24px; color:#061e5a; } label{ display:block; padding-bottom:5px; color:#F05519; font-weight:500; } input[type=email],input[type=password]{ border:1px solid #eeeeee; width:100%; height:30px; padding-left:4px; } button{ background:#061e5a; border:1px solid #061e5a; color:#ffffff; margin:10px 0px; padding:5px; } button:hover{ background:#F05519; border:1px solid #F05519; } .error-msg{ border:1px solid #ee0000; background:#ee0000; color:#ffffff; padding:2px; font-size:13px; } .success-msg{ border:1px solid #0ebc6f; background:#0ebc6f; color:#ffffff; font-size:13px; padding:2px; } .user-name{ color:#ee0000; } .logout-link{ margin-top:10px; display:block; background:#061e5a; border:1px solid #061e5a; color:#ffffff; width:48px; padding:5px; text-decoration:none; font-size:13px; } |
After Form Submit PHP Code: (index.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php require('config.php'); session_start(); if(isset($_POST['submit'])) { if((isset($_POST['email']) && $_POST['email'] !='') && (isset($_POST['password']) && $_POST['password'] !='')) { $email = trim($_POST['email']); $password = trim($_POST['password']); $sqlEmail = "select * from users where email = '".$email."'"; $rs = mysqli_query($conn,$sqlEmail); $numRows = mysqli_num_rows($rs); if($numRows == 1) { $row = mysqli_fetch_assoc($rs); if(password_verify($password,$row['password'])) { $_SESSION['user_id'] = $row['id']; $_SESSION['first_name'] = $row['first_name']; $_SESSION['last_name'] = $row['last_name']; header('location:dashboard.php'); exit; } else { $errorMsg = "Wrong Email Or Password"; } } else { $errorMsg = "No User Found"; } } } ?> |
I already mentioned that login form will be post on the same page so I wrote form submission code on the top of index.php
file. First I include config.php
file using require()
function. Then I start session by calling session_start()
function.
Always remember when you are working with sessions make sure that session_start() function must be placed on the top.
Afte that I used isset()
for form submit and then I make sure that email and password must have values in the next isset()
condition. Then I stored email and password using with trim()
function in the $email
and $password
variables respectively. $sqlEmail
is a mysql query which checks that email exists in the users table. $numRows
variable holds the msyql result count and if $numRows
returns 1 then I fetched that users records and store in $rows
variable.
password_verify()
function takes 2 parameters to verify user password. Parameter 1 is user submitted password and parameter 2 is already exist password.
If user submitted password and database password matches then I stored user id in $_SESSION['user_id']
variable, user first name in $_SESSION['first_name']
and user last name in $_SESSION['last_name']
and then I used header()
function for redirection and send user dashboard.php
page.
$errorMsg
variable is used to hold error messages.
Also read: PHP Contact Form with jQuery validation and Email sending code
After Successful Login: (Dashboard.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php session_start(); if(!isset($_SESSION)) { header('location:index.php'); exit; } ?> <!DOCTYPE html> <html> <head> <title>Dashboard | PHP Login and logout example with session</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container-dashboard"> Welcome to the dashboard! <span class="user-name"><?php echo ucwords($_SESSION['first_name'])?> <?php echo ucwords($_SESSION['last_name']);?> </span> <br> <a href="logout.php?logout=true" class="logout-link">Logout</a> </div> </body> </html> |
In dashboard.php
, I add session_start()
function then I add another condition that is, if $_SESSION
is not set then user will redirect to index.php
. This condition prevents dashboard.php
for not accessing without session.
After that there is a small chunk of html in which there is a welcome text with user name. And in the next line there is a logout button which goes to logout.php?logout=true
.
Session Destroy: (logout.php)
1 2 3 4 5 6 7 8 9 10 11 |
<?php if(isset($_GET['logout'])) { session_destroy(); header('location:index.php?logout=true'); exit; } ?> |
In logout.php
file, $_GET['logout']
is a query string that is coming from dashboard.php
page. session_destroy()
function destroys session variable and header()
function will send user to index.php
page.
Error Message: (index.php)
1 2 3 4 5 6 7 8 9 10 11 |
<?php if(isset($errorMsg)) { echo "<div class='error-msg'>"; echo $errorMsg; echo "</div>"; unset($errorMsg); } ?> |
Successfully Logout Message: (index.php)
1 2 3 4 5 6 7 8 9 10 11 |
<?php if(isset($_GET['logout'])) { echo "<div class='success-msg'>"; echo "You have successfully logout"; echo "</div>"; } ?> |
Right now there is a one user in the download code. Login id email is johndoe@example.com and password is john123. If you will face any problem please comment below on the post.
Also read:
wow really useful for me