php full session tutorial

Hey, There! “session” is an important concept in php, which we are going to study it full in this tutorial. The code will use a mysql Database with the php back end for user registration, login to portal, retrieving data from the database using session variables and logout. This tutorial will also use a redirect scheme to login page in case the user is not logged in.

Creating Database

So lets start this tutorial with the database. First of all, we’ll create a database with any name (in my case, it is Technopoints). execute the following SQL query inside database to create the table, rows and columns automatically.

CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`user_name` varchar(255) NOT NULL,
`user_email` varchar(40) NOT NULL,
`user_pass` varchar(255) NOT NULL,
`joining_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)

Connect with database

Now create the database file dbconfig.php like this tutorial and paste the following connection code in it.

<?php
class Database
{   
    private $host = "localhost";
    private $db_name = "technopoints";
    private $username = "root";
    private $password = "";
    public $conn;
   
    public function dbConnection()
	{
	    $this->conn = null;    
        try
		{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
			$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);	
        }
		catch(PDOException $exception)
		{
            echo "Connection error: " . $exception->getMessage();
        }
        return $this->conn;
    }
}
?>

Set sessions

Creating a structure of session

Now it is the time of creating session variables. create the file class.user.php with the following code. It has various functions to Login and Register the user. It is embedded in the class name “USER”.

<?php
require_once('dbconfig.php');
class USER
{	
	private $conn;
	public function __construct()
	{
		$database = new Database();
		$db = $database->dbConnection();
		$this->conn = $db;
    }
	
	public function runQuery($sql)
	{
		$stmt = $this->conn->prepare($sql);
		return $stmt;
	}
	
	public function register($uname,$umail,$upass)
	{
		try
		{
			$new_password = password_hash($upass, PASSWORD_DEFAULT);
			$stmt = $this->conn->prepare("INSERT INTO users(user_name,user_email,user_pass) 
		                                               VALUES(:uname, :umail, :upass)");							  
			$stmt->bindparam(":uname", $uname);
			$stmt->bindparam(":umail", $umail);
			$stmt->bindparam(":upass", $new_password);										  
				
			$stmt->execute();	
			
			return $stmt;	
		}
		catch(PDOException $e)
		{
			echo $e->getMessage();
		}				
	}
	
	
	public function doLogin($uname,$umail,$upass)
	{
		try
		{
			$stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass FROM users WHERE user_name=:uname OR user_email=:umail");
			$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
			$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
			if($stmt->rowCount() == 1)
			{
				if(password_verify($upass, $userRow['user_pass']))
				{
					$_SESSION['user_session'] = $userRow['user_id'];
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		catch(PDOException $e)
		{
			echo $e->getMessage();
		}
	}
	//modified function
	public function doLoginmod($name,$pass)
	{
		try
		{
			$stmt = $this->conn->prepare("SELECT name, password FROM admin WHERE name=:name OR password=:pass ");
			$stmt->execute(array(':name'=>$name));
			$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
			if($stmt->rowCount() == 1)
			{
				if(password_verify($pass, $userRow['password']))
				{
					$_SESSION['user_session'] = $userRow['name'];
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		catch(PDOException $e)
		{
			echo $e->getMessage();
		}
	}
	
	public function is_loggedin()
	{
		if(isset($_SESSION['user_session']))
		{
			return true;
		}
	}
	
	public function redirect($url)
	{
		header("Location: $url");
	}
	
	public function doLogout()
	{
		session_destroy();
		unset($_SESSION['user_session']);
		return true;
	}
}
?>

The above file will make all the session management. We have to create the further file as session.php to set the session after successful login.

Manage login and logout events

<?php
	session_start();
	require_once 'class.user.php';
	$session = new USER();
	// if user session is not active(not loggedin) this page will help 'home.php and profile.php' to redirect to login page
	// put this file within secured pages that users (users can't access without login)
	if(!$session->is_loggedin())
	{
		// session no set redirects to login page
		$session->redirect('index.php');
	}

Are you thinking in the above file has no “?>” php end tag? Actually,here no need of it as the file contains only php code.It will automatically ended. Thus, the session variables are ready to work.

Creating the main structure

Create login window

Now,lets design a homepage index.php and paste the following code in it.

<?php
session_start();
require_once("class.user.php");
$login = new USER();
if($login->is_loggedin()!="")
{
	$login->redirect('home.php');
}

if(isset($_POST['btn-login']))
{
	$uname = strip_tags($_POST['txt_uname_email']);
	$umail = strip_tags($_POST['txt_uname_email']);
	$upass = strip_tags($_POST['txt_password']);
		
	if($login->doLogin($uname,$umail,$upass))
	{
		$login->redirect('home.php');
	}
	else
	{
		$error = "<p><center>Wrong Details !</center></p>";
	}	
}
?>
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Technopoints:Login</title>
  <link rel='stylesheet prefetch' href='bootstrap/js/jquery-ui.css'>
  <link rel="stylesheet" href="bootstrap/css/style-new.css">  
</head>

<body>
<br/><br/><br/>
  <div class="login-card">
    <h1>Log-in</h1><br>
  <form method="post" id="login-form">
    <input type="text" name="txt_uname_email" placeholder="Username or E mail ID">
    <input type="password" name="txt_password" placeholder="Your Password">
    <input type="submit" name="btn-login" class="login login-submit" value="login">
  </form>
  <div class="login-help">
    <a href="sign-up.php">Register</a>
  </div>
</div>

<div id="error">
        <?php
			if(isset($error))
			{
				?>
                <div class="alert alert-danger">
                   <i class="glyphicon glyphicon-warning-sign"></i> &nbsp; <?php echo $error; ?> !
                </div>
                <?php
			}
		?>
        </div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
</body>
</html>

You’ll see the following look after opening this file.

php full session tutorial

Build Dashboard

Now we have to build the dashboard file where the user will be redirected after successful login. So, code home.php as follows.

<?php
	require_once("session.php");
	
	require_once("class.user.php");
	$auth_user = new USER();
	
	
	$user_id = $_SESSION['user_session'];
	
	$stmt = $auth_user->runQuery("SELECT * FROM users WHERE user_id=:user_id");
	$stmt->execute(array(":user_id"=>$user_id));
	//Image
	
	$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
	//unlink("user_images/".$userRow['userPic']);

?>
<!--<html>
<title>Technopoints Profile:<?php print($userRow['user_name']); ?></title>
<body>
<h1>Welcome, <?php print($userRow['user_name']); ?>!</h1>
<a href="logout.php?logout=true"><input type="submit" value="Logout"></a>-->

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome, <?php print($userRow['user_id'])?></title>
<link href="https://fonts.googleapis.com/css?family=Merienda+One" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="bootstrap/css/font-awesome.min.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap/css/style.css">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>

</head> 
<body>
<nav class="navbar navbar-default navbar-expand-xl navbar-light">
	<div class="navbar-header d-flex col">
		<a class="navbar-brand" href="#">Technopoints</a>  		
		<button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle navbar-toggler ml-auto">
			<span class="navbar-toggler-icon"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
		</button>
	</div>
	<!-- Collection of nav links, forms, and other content for toggling -->
	<div id="navbarCollapse" class="collapse navbar-collapse justify-content-start">
		<ul class="nav navbar-nav">
			<li class="nav-item active"><a href="#" class="nav-link">Home</a></li>
			<li class="nav-item"><a href="https://www.technopoints.co.in/about" class="nav-link">About</a></li>
			<li class="nav-item dropdown">
				<a data-toggle="dropdown" class="nav-link dropdown-toggle" href="#">Services <b class="caret"></b></a>
				<ul class="dropdown-menu">					
					<li><a href="#" class="dropdown-item">Web Design</a></li>
					<li><a href="#" class="dropdown-item">Web Development</a></li>
					<li><a href="#" class="dropdown-item">Graphic Design</a></li>
					<li><a href="#" class="dropdown-item">Digital Marketing</a></li>
				</ul>
			</li>
			<li class="nav-item"><a href="https://www.technopoints.co.in" class="nav-link">Blog</a></li>
			<li class="nav-item"><a href="https://www.technopoints.co.in/contact" class="nav-link">Contact</a></li>
		</ul>
		<form class="navbar-form form-inline">
			<div class="input-group search-box">								
				<input type="text" id="search" class="form-control" placeholder="Search by Name">
				<span class="input-group-addon"><i class="material-icons">&#xE8B6;</i></span>
			</div>
		</form>
		<ul class="nav navbar-nav navbar-right ml-auto">
			<li class="nav-item dropdown">
				<a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle user-action"><img src="images/default-pic.png" class="avatar" alt="Avatar"> <?php print($userRow['user_name']); ?> <b class="caret"></b></a>
				<ul class="dropdown-menu">
					<li><a href="logout.php?logout=true" class="dropdown-item"><i class="material-icons">&#xE8AC;</i> Logout</a></li>
				</ul>
			</li>
		</ul>
	</div>
</nav>
<center>
<h1>Welcome, <?php print($userRow['user_name']) ?></h1>
<br/><br/><br/>
<img src="images/default-pic.png"/>
<h3>Name:<?php print($userRow['user_name']) ?></h3>
<h3>Email: <?php print($userRow['user_email']) ?></h3>
<h3>User ID: <?php print($userRow['user_id']) ?></h3>
<button class="button button1" onclick="window.location.href='logout.php?logout=true'">Logout</button>
</center>
</body>
</html>

As a result of above code, you’ll see the following view after successful login.

php full session tutorial login window

In the login view, there is Logout button. In order to unset the session and redirect the user to login page, we create the following file as logout.php.

<?php
	require_once('session.php');
	require_once('class.user.php');
	$user_logout = new USER();
	
	if($user_logout->is_loggedin()!="")
	{
		$user_logout->redirect('home.php');
	}
	if(isset($_GET['logout']) && $_GET['logout']=="true")
	{
		$user_logout->doLogout();
		$user_logout->redirect('index.php');
	}

Creating Registration form

Now, we will also include the facility to create the new user and assign the separate panel to it. so create file sign-up.php and paste the following code in it.

<?php
session_start();
require_once('class.user.php');
$user = new USER();

if($user->is_loggedin()!="")
{
	$user->redirect('home.php');
}

if(isset($_POST['btn-signup']))
{
	$uname = strip_tags($_POST['txt_uname']);
	$umail = strip_tags($_POST['txt_umail']);
	$upass = strip_tags($_POST['txt_upass']);	
	
	if($uname=="")	{
		$error[] = "provide username !";	
	}
	else if($umail=="")	{
		$error[] = "provide email id !";	
	}
	else if(!filter_var($umail, FILTER_VALIDATE_EMAIL))	{
	    $error[] = 'Please enter a valid email address !';
	}
	else if($upass=="")	{
		$error[] = "provide password !";
	}
	else if(strlen($upass) < 6){
		$error[] = "Password must be atleast 6 characters";	
	}
	else
	{
		try
		{
			$stmt = $user->runQuery("SELECT user_name, user_email FROM users WHERE user_name=:uname OR user_email=:umail");
			$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
			$row=$stmt->fetch(PDO::FETCH_ASSOC);
				
			if($row['user_name']==$uname) {
				$error[] = "<center>sorry username already taken !</center>";
			}
			else if($row['user_email']==$umail) {
				$error[] = "<center>sorry email id already taken !</center>";
			}
			else
			{
				if($user->register($uname,$umail,$upass)){	
					$user->redirect('sign-up.php?joined');
				}
			}
		}
		catch(PDOException $e)
		{
			echo $e->getMessage();
		}
	}	
}

?>
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Technopoints:Signup</title>
  
  
  <link rel='stylesheet prefetch' href='bootstrap/js/jquery-ui.css'>
  <link rel="stylesheet" href="bootstrap/css/style-new.css">

  
</head>

<body>
<br/><br/><br/>
  <div class="login-card">
    <h1>Signup</h1><br>
  <form method="post" id="login-form">
        <?php
			if(isset($error))
			{
			 	foreach($error as $error)
			 	{
					 ?>
                     <div class="alert alert-danger">
                        <i class="glyphicon glyphicon-warning-sign"></i> &nbsp; <?php echo $error; ?>
                     </div>
                     <?php
				}
			}
			else if(isset($_GET['joined']))
			{
				 ?>
                 <div class="alert alert-info">
                      <i class="glyphicon glyphicon-log-in"></i> &nbsp; Successfully registered <a href='index.php'>login</a> here
                 </div>
                 <?php
			}
		?>
    <input type="text" name="txt_uname" placeholder="Enter Username" value="<?php if(isset($error)){echo $uname;}?>" />
    <input type="text" name="txt_umail" placeholder="Enter Email" value="<?php if(isset($error)){echo $umail;}?>"/>
	<input type="password" class="form-control" name="txt_upass" placeholder="Enter Password" />
    <input type="submit" name="btn-signup" class="login login-submit" value="Sign Up" />
  </form>
    
  <div class="login-help">
    Already Registered? <a href="index.php">Login Here</a>
  </div>
</div>

<div id="error">
        <?php
			if(isset($error))
			{
				?>
                <div class="alert alert-danger">
                   <i class="glyphicon glyphicon-warning-sign"></i> &nbsp; <?php echo $error; ?> !
                </div>
                <?php
			}
		?>
        </div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
</body>
</html>

See the signup form below. After filling the details and clicking on sign up button, user registration will be done.

php full session tutorial registration window

Finally, add styling by provided some css files for a better look. Following style.css will cover it.

body{
		background: #eeeeee;
	}
    .form-inline {
        display: inline-block;
    }
	.navbar-header.col {
		padding: 0 !important;
	}	
	.navbar {		
		background: #fff;
		padding-left: 16px;
		padding-right: 16px;
		border-bottom: 1px solid #d6d6d6;
		box-shadow: 0 0 4px rgba(0,0,0,.1);
	}
	.nav-link img {
		border-radius: 50%;
		width: 36px;
		height: 36px;
		margin: -8px 0;
		float: left;
		margin-right: 10px;
	}
	.navbar .navbar-brand {
		color: #555;
		padding-left: 0;
		padding-right: 50px;
		font-family: 'Merienda One', sans-serif;
	}
	.navbar .navbar-brand i {
		font-size: 20px;
		margin-right: 5px;
	}
	.search-box {
        position: relative;
    }	
    .search-box input {
		box-shadow: none;
        padding-right: 35px;
        border-radius: 3px !important;
    }
	.search-box .input-group-addon {
        min-width: 35px;
        border: none;
        background: transparent;
        position: absolute;
        right: 0;
        z-index: 9;
        padding: 7px;
		height: 100%;
    }
    .search-box i {
        color: #a0a5b1;
		font-size: 19px;
    }
	.navbar .nav-item i {
		font-size: 18px;
	}
	.navbar .dropdown-item i {
		font-size: 16px;
		min-width: 22px;
	}
	.navbar .nav-item.open > a {
		background: none !important;
	}
	.navbar .dropdown-menu {
		border-radius: 1px;
		border-color: #e5e5e5;
		box-shadow: 0 2px 8px rgba(0,0,0,.05);
	}
	.navbar .dropdown-menu li a {
		color: #777;
		padding: 8px 20px;
		line-height: normal;
	}
	.navbar .dropdown-menu li a:hover, .navbar .dropdown-menu li a:active {
		color: #333;
	}	
	.navbar .dropdown-item .material-icons {
		font-size: 21px;
		line-height: 16px;
		vertical-align: middle;
		margin-top: -2px;
	}
	.navbar .badge {
		background: #f44336;
		font-size: 11px;
		border-radius: 20px;
		position: absolute;
		min-width: 10px;
		padding: 4px 6px 0;
		min-height: 18px;
		top: 5px;
	}
	.navbar ul.nav li a.notifications, .navbar ul.nav li a.messages {
		position: relative;
		margin-right: 10px;
	}
	.navbar ul.nav li a.messages {
		margin-right: 20px;
	}
	.navbar a.notifications .badge {
		margin-left: -8px;
	}
	.navbar a.messages .badge {
		margin-left: -4px;
	}	
	.navbar .active a, .navbar .active a:hover, .navbar .active a:focus {
		background: transparent !important;
	}
	@media (min-width: 1200px){
		.form-inline .input-group {
			width: 300px;
			margin-left: 30px;
		}
	}
	@media (max-width: 1199px){
		.form-inline {
			display: block;
			margin-bottom: 10px;
		}
		.input-group {
			width: 100%;
		}
	}
h1{
	font-family: "Comic Sans MS", cursive, sans-serif;
	text-shadow: 2px 2px #ff0000;
	color: #80E15D;
	padding-top: 20px;
}
h3{
	font-family: "Comic Sans MS", cursive, sans-serif;
	color:	#DC143C;
}

img {
  border-radius: 50%;
  width: 200px;
  height: 200px;
}
.button {
    background-color: #8B008B; /* Purple */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    -webkit-transition-duration: 0.4s; /* Safari */
    transition-duration: 0.4s;
}
.button1:hover {
    box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}

Also you can get additional almost all css files after downloading the zip file below. Probably, it will not impact the back end performance.
That’s it! Now we have built the complete login and signup system using php and mysql backend.
Hope you liked it. Stay tuned for more tutorial 🙂

If you have any difficulties in this tutorial, feel free to download the source code from below link.

Download Source Code

4 thoughts on “php full session tutorial

  1. L
    Lina says:

    Thank you for the good writeup. It in fact was a amusement account
    it. Look advanced tto more added agreeable from you!However,
    how could we communicate?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.