PHP

PHP Login Registration – State Management

PHP State Management

Description

State Management is the basic need for any dynamic application, here I am going to explain How to manage sessions in PHP using a simple register and login application which is going to help on to get better understandings.

Let’s get started:

Setup Database tables

First step is to setup a database table to store users login details, so go ahead and create following table.

 

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
);
Table Structure

index.php

Create a new index.php page in a root directory of the project and add the following code. If you notice the code we are just having a link to `login` and `registration` page with the little information about the project as this just our basic demo project.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home | iTech Empires: PHP State Management Tutorial</title>

<!-- Bootstrap CSS File -->
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Home</h2>

<a href="https://cdn.itechempires.com/wp-content/uploads/2016/03/index.php">Home</a> | <a href="login.php">Login</a> | <a href="register.php">Register</a>
<p>
iTech Empires PHP State Management Tutorial.
</p>
</div>
</div>
</div>
</body>
</html>

I am going to consider you have your basic setup ready with the database and `users` table along with the index.php page, lets move on to the next step.

register.php Page

`register.php` page is to have a registration feature, so that user can create their account for login and use the system, go ahead and use following code after creating your page.

<?php

session_start(); // REQUIRED TO BE USED SESSION
if(isset($_SESSION['id']))
{
header("location: user_profile.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register | iTech Empires: PHP State Management Tutorial</title>

<!-- Bootstrap CSS File -->
<link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<h2>Register</h2>
<p>
<a href="https://cdn.itechempires.com/wp-content/uploads/2016/03/index.php">Home</a> | <a href="login.php">Login</a> | <a href="register.php">Register</a>
</p>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" class="form-control" placeholder="First Name" id="first_name">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" class="form-control" placeholder="Last Name" id="last_name">
</div>
</div>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input type="email" class="form-control" placeholder="Email Address" id="email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" placeholder="Password" id="password">
</div>
<div class="form-group">
<label for="confirm_password">Password</label>
<input type="password" class="form-control" placeholder="Confirm Password" id="confirm_password">
</div>
<div class="form-group">
<button >

If you look at the code from the above page, we have PHP as well html code added, so we are using PHP to check if user already login to the system or not, if user is login then redirect the user to the profile page. keep in mind if you need to use sessions variables throughout the PHP page, we need to start the session at the top of the page using `session_start();` function, to be able to get or set the session variable(s) value.

Next we have basic registration form fields along with the Register button which is calling javascript function with `onclick` event. this is the function to validate our registration form and submit the information to the server. let’s create our `script.js` file and defined the function.

script.js file

Look at the following code, here we are validating each field from our registration page and sending the information to the server using AJAX, (I have added AJAX here instead of form submit feature, I just wanted to demonstrate the extra step so that you can lean AJAX as well, feel free to ask question about it in the comment box below.)

`script.js`:

/*
* iTech Empires - PHP State Management Script
* Version 1.0.0
*/
function register()
{
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
var password = $("#password").val();
var confirm_password = $("#confirm_password").val();

if(first_name == "")
{
alert("First name field is required!");
}
else if(last_name == "")
{
alert("Last name field is required!");
}
else if(email == "")
{
alert("Email field is required!");
}
else if(password == "")
{
alert("Password field is required!");
}
else if(confirm_password == "")
{
alert("Confirm Password field is required!");
}
else if(confirm_password != password)
{
alert("Invalid Confirm password!");
}
else
{
$.post("script/register_user.php", {
first_name: first_name,
last_name: last_name,
email: email,
password: password
}, function(data, status){
alert(data);
$(".form-control").val('');
});
}
}

script/register_user.php page

As we see we need PHP page called `register_user.php` for AJAX call to register new user so lets create our required page to complete ajax call and to be able to register user.

Register the user is basically means to add new record in to the database, so what we are doing actually is:

  1. Getting the Request from User Interface
  2. Adding it to the database table
  3. Responding with the message.

`register_user.php`:

<?php

include("db_connection.php");

$first_name = mysqli_real_escape_string($con, $_POST['first_name']);
$last_name = mysqli_real_escape_string($con, $_POST['last_name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5(mysqli_real_escape_string($con, $_POST['password']));

// regiser user 
  $query = "INSERT INTO users(first_name, last_name, email, password) 
VALUES('$first_name', '$last_name', '$email', '$password')";
if(!mysqli_query($con, $query))
{
 exit(mysqli_error($con));
}
else
{
 echo "Your registration is successfully, Please login!";
}
?>

Whenever we need to interact with mysql we are going to need database connection script, so the better practice is to keep connection code in separate file and use it whenever required sounds good right? Yes it does it’s better you keep this practice while working with Core PHP Project, get back to the tutorial so here we are doing same thing go ahead and create `db_connection.php` file and add following code, don’t forgot to replace the connection variables values as per you system setup.

`db_connection.php`:

<?php

// Connection variables 
$host = "localhost"; // MySQL host name eg. localhost
$user = "root"; // MySQL user. eg. root ( if your on localserver)
$password = ""; // MySQL user password  (if password is null for your root user then keep it empty )
$database = "test_db"; // MySQL Database name

// Connect to MySQL Database 
$con = new mysqli($host, $user, $password, $database);

// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} 
?>

Login Page

What is Login? if you,re new in the development field, you might think what does Login to the system means? so login is actually to enter into the system, the login page is the entry gate of the application with the Lock, and the User has to remember the key that is Password which is generated while creating the new account on registration page, simple snuff right? if not I am going to make it simple for you.

So, Let’s provide our users to be able to do the same, go ahead and use following code to create your Login page.

`login.php`

<?php
/*
* iTech Empires: PHP State Management Script 
* Version: 1.0.0
* Page: Login
*/ 

 session_start(); // starting a session 

 // check session is set (if user is already login, redirect to the profile page)
 if($_SESSION['id'])
 {
  header("location: user_profile.php");
  exit;
 }

 $error_message = "";
 // check for form submit action 
 if(isset($_POST['email']) && isset($_POST['password']))
 {
  // basic input validation
  if($_POST['email'] == "" && $_POST['password'] == "")
  {
   $error_message = "Please enter your login details!";
  }
  else
  {
   // validate user ( if successfully validated, redirect to the profile page)
   include("script/db_connection.php");
   $email = mysqli_real_escape_string($con, $_POST['email']);
   $password = md5(mysqli_real_escape_string($con, $_POST['password']));

   $query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
   if(!$result = mysqli_query($con, $query))
   {
    exit(mysqli_error($con));
   }

   if(mysqli_num_rows($result) > 0)
   {
    // Login successfully
    while($row = mysqli_fetch_assoc($result))
    {
     // set sessions variable with the user details
     $_SESSION['id'] =  $row['id'];
     $_SESSION['first_name'] =  $row['first_name'];
     $_SESSION['last_name'] =  $row['last_name'];
     $_SESSION['email'] =  $row['email'];
    }

    // redirect to the secure page ex. user profile 
    header("location: user_profile.php");
    exit;
   }
   else
   {
    // show error message
    $error_message = "Invalid login details, Please try again!";
   }
  }
 }
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Login | iTech Empires: PHP State Management Tutorial</title>

 <!-- Bootstrap CSS File  -->
 <link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css" />
</head>
<body>
 <div class="container">
  <div class="row">
   <div class="col-md-6">
    <h2>Login</h2>
    <p>
     <a href="https://cdn.itechempires.com/wp-content/uploads/2016/03/index.php">Home</a> | <a href="login.php">Login</a> | <a href="register.php">Register</a>
    </p>
    <form method="post" action="login.php">
     <div class="form-group">
      <?php 
       // show error message
       echo $error_message 
      ?>
     </div>
     <div class="form-group">
      <label for="email">Email Address</label>
      <input type="email" class="form-control" placeholder="Email Address" name="email">
     </div>
     <div class="form-group">
      <label for="password">Password</label>
      <input type="password" class="form-control" placeholder="Password" name="password">
     </div>
     <div class="form-group">
      <button type="submit" class="btn btn-primary">Login</button>
     </div>
    </form>
   </div>
   <div class="col-md-6"></div>
  </div>
 </div>
 <!-- Jquery JS file -->
 <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
</body>
</html>

`Did you checked above code or just copied?`

So here is the thing why I am asking this question is because, I want to make sure you get each point of my tutorial. what we do in the backend while processing the login request? here is the answer:

  1. Ask user for Login details
  2. Validate them by submitting to the server ( match with existing or available records from the database )
  3. If match found: Fetch User basis details like ID, Name and store it to the session variable and redirect the user to the profile page.
  4. If the details are invalid: Get back to the login with the error message.

Move on to the next step.

user_profile.php page

After getting successful login we need to welcome greetings for the demo, you can use it into your existing application and display the profiles as per your requirements.

<?php
session_start(); // REQUIRED TO BE USED SESSION VARIABLES
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Profile</title>
</head>
<body>

<h2>User Profile</h2>

<h3>Welcome, <?php echo $_SESSION['first_name']; ?></h3>

<p>My Details: </p>
<p>
Full Name: <?php echo $_SESSION['first_name']. " ". $_SESSION['last_name']; ?>
</p>
<p>
Email: <?php echo $_SESSION['email']; ?>
</p>
<p>
<a href="logout.php?logout=true">Logout</a>
</p>
</body>
</html>

logout.php page

Logout user by destroying the php sessions:

<?php

session_start();

if(isset($_GET['logout']) == true)
{
session_destroy();
header("location: login.php");
exit;
}

?>

Folder Structure

Here is the folder structure for this tutorial:

 

You can download complete source code:

If you find this tutorial useful please share and let me know your feedback in comment box below:

Recommendation:  

You also learn to create login registration system using PDO – Login Registration System with PHP Data Object (PDO)

Yogesh Koli

Software engineer & Blogger live in India, has 8+ years of experience working with the Front-end and Back-end Web Application Development.

Recent Posts

Complete guide of using Laravel 6 Eloquent Subquery Enhancements

Learn How to use laravel frameworks new improved feature called Eloquent Subquery and get example…

2 years ago

3 Useful examples of using Array Map function in PHP – Best Practices

Learn how to use php array map function with easy and essential tutorial to modify…

2 years ago

Working with PHP Array Filter Function – Best Practices

Learn how to use php array filter function with easy and essential tutorial to filter…

2 years ago

How to add Access Modifiers with Constructor Parameters in TypeScript

Want to know how to refactor your Typescript class, Learn here utilising Typescript of the…

2 years ago

What is Access Modifiers and how to use Access Modifiers in TypeScript ?

What is Access Modifiers in typescript, how to use Access Modifiers, when to use them,…

2 years ago

Top 10 Super Useful Packages to Improve Laravel applications in 2019

This tutorial provide ultimate list of package those are top 10 on packagist and super…

2 years ago