Login Logout Example Using Sessions In PHP



Tutorial On Login Logout Example Using Sessions In PHP

Hello friends, I am back with yet another exciting tutorial on login logout example using session in php. Sessions are an essential part in any login and logout form of any website or application. So lets start with the step by step tutorial on login logout example using sessions in PHP.

STEP 1:

Create 5 files as followed:

  • config.php
  • style.css
  • index.php
  • login.php
  • welcome.php
  • logout.php

 

STEP 2:

We have created 1 database named ‘projects’ and have 1 table named “test_user”.

Now create a config.php file.

<?php $db_hostname = 'localhost'; // Database hostname $db_username = 'root'; // Database username $db_password = ''; // Database password $db_name = 'test'; // Database name $conn = mysqli_connect($db_hostname, $db_username, $db_password, $db_name); if(!$conn) { echo "Unable to connect database".mysqli_error($conn);die; } else { echo "Database connected successfully"; } ?>;

STEP 3:

Next, create a login form inside ‘index.php’

<!DOCTYPE html>
<html>
<head>
    <title>Login form using php</title>
<link rel="stylesheet" type="text/css" href="style.css">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%20src%3D%22jquery-1.11.1.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
<!-- <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%20src%3D%22main.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" /> -->
</head>
<body> 
<?php session_start(); if(isset($_SESSION['email']) &amp;amp;&amp;amp; !empty($_SESSION['email'])) { header('location:welcome.php'); } $error = [ "email_error" => '',
"password_error" => '',
"error_msg" => ''
];
 
$form_data = [
"email" => '',
"password" => ''
];
 
if(!empty($_SESSION['error']))
{
    $error = $_SESSION['error'];
}
 
if(!empty($_SESSION['form_data']))
{
    $form_data = $_SESSION['form_data'];
}
 
?>
<h1><center>Login form using php</center></h1>
<form action="submit.php" method="post" onsubmit="return validate();" id="form_submission_ajax">
<table class="form-table">
<tr>
<td><label>Email:</label></td>
<td><input type="email" name="email" id="email" value="<?php echo $form_data['email']; ?>"></td>
</tr>
<tr>
<td></td>
<td id="email_error" class="error"><?php echo $error['email_error']; ?></td>
</tr>
<tr>
<td><label>Password:</label></td>
<td><input type="password" name="password" id="password" value="<?php echo $form_data['email']; ?>"></td>
</tr>
<tr> 
<td></td>
<td id="password_error" class="error"><?php echo $error['password_error']; ?></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
<td></td>
<td class="error"><?php echo $error['error_msg']; ?></td>
</tr>
<tr>
<td></td>
<td>Test Email : test@test.com</td>
</tr>
<tr>
<td></td>
<td>Test Password : abcd</td>
</tr>
</table>
</form>
</body>
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0Afunction%20validate()%0A%7B%0A%20%20%20%20var%20valid%20%3D%20true%3B%0A%20%20%20%20var%20email%20%3D%20%24('%23email').val()%3B%0A%20%20%20%20var%20password%20%3D%20%24('%23password').val()%3B%0A%20%0A%20%20%20%20if(email%3D%3D''%20%7C%7C%20email%3D%3Dnull)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20valid%3Dfalse%3B%0A%20%20%20%20%20%20%20%20%24('%23email_error').html(%22*%20Please%20enter%20email.%22)%3B%0A%20%20%20%20%7D%0A%20%20%20%20else%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%24('%23email_error').html(%22%22)%3B%20%0A%20%20%20%20%7D%0A%20%0A%20%20%20%20if(password%3D%3D''%20%7C%7C%20password%3D%3Dnull)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20valid%3Dfalse%3B%0A%20%20%20%20%20%20%20%20%24('%23password_error').html(%22*%20Please%20enter%20password.%22)%3B%0A%20%20%20%20%7D%0A%20%20%20%20else%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%24('%23password_error').html(%22%22)%3B%0A%20%20%20%20%7D%0A%20%0A%20%20%20%20if(valid%3D%3Dfalse)%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20return%20false%3B%0A%20%20%20%20%7D%0A%20%20%20%20else%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20return%20true%3B%0A%20%20%20%20%7D%0A%7D%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
</html>   
 
<?php $_SESSION['error'] = ""; $_SESSION['form_data'] = ""; ?>

 

STEP 4:

Then create a login.php file.

Now when user clicks on the Submit button in index.php file, it will redirect the data into login.php file. Login.php file will check if email and password entered matches or not. If not then it will throw an error with appropriate message.

See my login.php file

<?php session_start(); $valid = true; $error = []; $form_data = []; if(!empty($_POST['email'])) { $email = $_POST['email']; $email_data = array("email" => $email);
    $form_data = array_merge($form_data, $email_data);
    $email_error = array("email_error" => "");
    $error = array_merge($error, $email_error);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
    {
        $valid = false;
        $email_error = array("email_error" => "* Valid emial format is 'abc@xxxx.com'.");
        $error = array_merge($error, $email_error);
    }
}
else
{
    $valid = false;
    $email = "";
    $email_data = array("email" => $email);
    $form_data = array_merge($form_data, $email_data);
    $email_error = array("email_error" => "* Email is required.");
    $error = array_merge($error, $email_error);
}
 
if(!empty($_POST['password']))
{
    $password = md5($_POST['password']);
    $password_data = array("password" => $password);
    $form_data = array_merge($form_data, $password_data);
    $password_error = array("password_error" => "");
    $error = array_merge($error, $password_error);
}
else
{
    $valid = false;
    $password = "";
    $password_data = array("password" => $password);
    $form_data = array_merge($form_data, $password_data);
    $password_error = array("password_error" => "* Password is required.");
    $error = array_merge($error, $password_error);
}
 
if($valid == true)
{
    include 'config.php';
    mysqli_select_db($conn, $db_name);
    $sql = "SELECT * FROM test_user WHERE email ='$email' AND password='$password'";
    $query = mysqli_query($conn, $sql);
    if(!$query)
    {
        echo "Query does not exist.";
        die;
    }
    $row = mysqli_num_rows($query);
    if($row==1)
    {
        $_SESSION['email'] = $email;
        header('Location:welcome.php');  
    }
    else
    {
        $error_msg = array("error_msg" => "* Your email and password does not match.");
        $error = array_merge($error, $error_msg);
        $_SESSION['error'] = $error;
        $_SESSION['form_data'] = $form_data;
        header('Location:index.php');       
    }
}
else
{
    $error_msg = array("error_msg" => "* Please fill the information.");
    $error = array_merge($error, $error_msg);
    $_SESSION['error'] = $error;
    $_SESSION['form_data'] = $form_data;
    header('Location:index.php');
}
?>

 

STEP 5:

Now create welcome.php file.

If username and password matches then it will get stored in the session and displayed in welcome.php file.

<?php session_start(); if(!isset($_SESSION['email']) &amp;amp;&amp;amp; empty($_SESSION['email'])) { header('location:index.php'); } ?>


<h2>Welcome <?php echo $_SESSION['email']; ?></h2>


You have successfully logged in. Thank you!
You can <a href="logout.php">Logout</a> from here.

 

STEP 6:

Finally create a logout.php file to destroy the session.

<?php session_start(); $_SESSION['email'] = ''; unset($_SESSION['email']); session_destroy(); header('location:index.php'); ?>

Don’t forget to share your doubts in the comment box and also share this post on social media and with your friends becaus“You share, I share, let’s make the world aware”.

You may want to take a look at the following related posts:

Also for more awesome tutorials, please don’t forget to like our facebook page TryCatch Classes.

Bonus: We also give training on following topics:

                      1. Codeigniter Training  in Mumbai .

2. Web Designing Training in Mumbai.

3. Bootstrap Training Course in Mumbai.

4. UI / UX Training.

5. IOS Training Institute in Mumbai.