
Table of Contents
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.
1 2 3 4 5 6 7 8 |
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`) ); |

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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!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.
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 |
<?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 onclick="register()" class="btn btn-primary">Register</button> </div> </div> <div class="col-md-6"></div> </div> </div> <!-- Jquery JS file --> <script src="js/script.js" type="text/javascript"></script> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> </body> </html> |
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
:
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 |
/* * 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:
- Getting the Request from User Interface
- Adding it to the database table
- Responding with the message.
register_user.php
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?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
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?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
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 95 96 97 98 99 100 101 102 103 104 105 106 |
<?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:
- Ask user for Login details
- Validate them by submitting to the server ( match with existing or available records from the database )
- 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.
- 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.
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 |
<?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:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?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)