How To Create user Registration and Login Script with PHP and MySQLi

In this tutorial we are going to share simple User registration and Login Script using PHP and mysql If you are konw besic php and want to start your first PHP project where users can register and login then you must create a secure login system for your website so that you can allow users to login to your website without any hassle. We can create a login system in PHP very easily, and we’ll need to have a MySQLi database and table in order to save the user information such as user name, user email and user password etc. After we have a table to store users then we can create a script in PHP for verifying the users who want to sign in to our website.

Login and Registration System using PHP with the improved MySQLi. it’s a simple script which you can easily understand. for the designing purpose i have used here bootstrap to create login and signup form which is simple and easy to create with the help of bootstrap, if you are using PHP5.5 then you must use new password hashing function, you can see it how to use them here in this tutorial, php User registration Login script with MySQL .

Create the Database for Users Registration Login

The first step for creating User registration Login script with PHP MySQL is to create a database inside PHPMyAdmin and create a database with the name “alshibli_nafis ”,  and copy the below sql code and past in to the SQL to create user table

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(5) NOT NULL AUTO_INCREMENT,
  `username` varchar(25) NOT NULL,
  `email` varchar(35) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
config.Php

This page contains code for connection your webpage to mysql database using MySQLi extension, here’s how you can use MySQLi an improved extension with your MySQL Database

<?php

  $DB_host = "localhost";
  $DB_user = "ualshibli_nf";
  $DB_pass = "";
  $DB_name = "alshibli_nafis ";
  
  $MySQLi_CON = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);
    
     if($MySQLi_CON->connect_errno)
     {
         die("ERROR : -> ".$MySQLi_CON->connect_error);
     }

?>
register.php

Now we will create  our registration/signup page for the new user anyone who are want login our webpage they will first need to register username and password this page is for register new user it will ask username, email and password to enter, i have skipped here validation part and used HTML5 required client side validations to validate the form and the form was created with bootstrap. password_hash($upass, PASSWORD_DEFAULT);

<?php
session_start();
if(isset($_SESSION['userSession'])!="")
{
 header("Location: home.php");
}
include_once 'config.Php';

if(isset($_POST['btn-signup']))
{
 $uname = $MySQLi_CON->real_escape_string(trim($_POST['user_name']));
 $email = $MySQLi_CON->real_escape_string(trim($_POST['user_email']));
 $upass = $MySQLi_CON->real_escape_string(trim($_POST['password']));
 
 $new_password = password_hash($upass, PASSWORD_DEFAULT);
 
 $check_email = $MySQLi_CON->query("SELECT email FROM users WHERE email='$email'");
 $count=$check_email->num_rows;
 
 if($count==0){
  
  
  $query = "INSERT INTO users(username,email,password) VALUES('$uname','$email','$new_password')";

  
  if($MySQLi_CON->query($query))
  {
   $msg = "<div class='alert alert-success'>
      <span class='glyphicon glyphicon-info-sign'></span> &nbsp; successfully registered !
     </div>";
  }
  else
  {
   $msg = "<div class='alert alert-danger'>
      <span class='glyphicon glyphicon-info-sign'></span> &nbsp; error while registering !
     </div>";
  }
 }
 else{
  
  
  $msg = "<div class='alert alert-danger'>
     <span class='glyphicon glyphicon-info-sign'></span> &nbsp; sorry email already taken !
    </div>";
   
 }
 
 $MySQLi_CON->close();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login & Registration System</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen"> 
<link rel="stylesheet" href="style.css" type="text/css" />

</head>
<body>

<div class="signin-form">

 <div class="container">
     
        
       <form class="form-signin" method="post" id="register-form">
      
        <h2 class="form-signin-heading">Sign Up</h2><hr />
        
        <?php
  if(isset($msg)){
   echo $msg;
  }
  else{
   ?>
            <div class='alert alert-info'>
    <span class='glyphicon glyphicon-asterisk'></span> &nbsp; all the fields are mandatory !
   </div>
            <?php
  }
  ?>
          
        <div class="form-group">
        <input type="text" class="form-control" placeholder="Username" name="user_name" required  />
        </div>
        
        <div class="form-group">
        <input type="email" class="form-control" placeholder="Email address" name="user_email" required  />
        <span id="check-e"></span>
        </div>
        
        <div class="form-group">
        <input type="password" class="form-control" placeholder="Password" name="password" required  />
        </div>
        
      <hr />
        
        <div class="form-group">
            <button type="submit" class="btn btn-default" name="btn-signup">
      <span class="glyphicon glyphicon-log-in"></span> &nbsp; Create Account
   </button> 
            
            <a href="index.php" class="btn btn-default" style="float:right;">Log In Here</a>
            
        </div> 
      
      </form>
    </div>
</div>
</body>
</html>

Index.Php

this page is our login page for those your who are already register at our website using register.php page  this login page will ask users to enter email and password to go the home page which is members page, to use database we have to include “config.php” file. i have used here password_verify($upass, $row[‘password‘]) to verify password this is new password hashing function and you have to use PHP5.5 to use this function.

<?php
session_start();
include_once 'config.php';

if(isset($_SESSION['userSession'])!="")
{
 header("Location: dashboard.php");
 exit;
}

if(isset($_POST['btn-login']))
{
 $email = $MySQLi_CON->real_escape_string(trim($_POST['user_email']));
 $upass = $MySQLi_CON->real_escape_string(trim($_POST['password']));
 
 $query = $MySQLi_CON->query("SELECT * FROM users WHERE email='$email'");
 $row=$query->fetch_array();
 
 if(password_verify($upass, $row['password']))
 {
  $_SESSION['userSession'] = $row['user_id'];
  header("Location: home.php");
 }
 else
 {
  $msg = "
        email or password does not exists !
    ";
 }
 
 $MySQLi_CON->close();
 
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen"> 
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>

<div class="signin-form">

 <div class="container">
     
        
       <form class="form-signin" method="post" id="login-form">
      
        <h2 class="form-signin-heading">Sign In.</h2><hr />
        
        <?php
  if(isset($msg)){
   echo $msg;
  }
  ?>
        
        <div class="form-group">
        <input type="email" class="form-control" placeholder="Email address" name="user_email" required />
        <span id="check-e"></span>
        </div>
        
        <div class="form-group">
        <input type="password" class="form-control" placeholder="Password" name="password" required />
        </div>
       
      <hr />
        
        <div class="form-group">
            <button type="submit" class="btn btn-default" name="btn-login" id="btn-login">
      <span class="glyphicon glyphicon-log-in"></span> &nbsp; Sign In
   </button> 
            
            <a href="register.php" class="btn btn-default" style="float:right;">Sign UP Here</a>
            
        </div>  
      </form>
    </div>
</div>
</body>
</html>

Dashboard.php

User who are alredy register at our website if he/she enter right username and password then regitred user will be successfully logged in he/she will be redirected to this “Dashboard.php” page, this is members page only registered users can access this page, contains bootstrap header with menu and one link to logout. this page shows welcome message of logged in user with username and a hyper link to logout the user and redirects the ‘logout.php’ page

<?php
session_start();
include_once 'config.php';

if(!isset($_SESSION['userSession']))
{
 header("Location: index.php");
}

$query = $MySQLi_CON->query("SELECT * FROM users WHERE user_id=".$_SESSION['userSession']);
$userRow=$query->fetch_array();
$MySQLi_CON->close();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['email']; ?></title>

<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> 
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen"> 

<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>

<nav class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="http://www.alshibli_nafis blogger.com/">alshibli_nafis  Blogger</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li><a href="http://www.alshibli_nafis blogger.com/category/learn_php_programming/">PHP</a></li>
            <li><a href="http://www.alshibli_nafis blogger.com/category/wordpress-tutorials/">WordPress</a></li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#"><span class="glyphicon glyphicon-user"></span>&nbsp; <?php echo $userRow['username']; ?></a></li>
            <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp; Logout</a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>

<div class="container" style="margin-top:150px;text-align:center;font-family:Verdana, Geneva, sans-serif;font-size:35px;">
 <a href="http://www.alshibli_nafis blogger.com/">alshibli_nafis  Blogger</a><br /><br />
    
</div>

</body>
</html>

Logout.Php

this page to logout the users when user click one the logout page user will be  redirects to the login/index page. it will destroys the current logged in users session

<?php
session_start();

if(!isset($_SESSION['userSession']))
{
 header("Location: index.php");
}
else if(isset($_SESSION['userSession'])!="")
{
 header("Location: Dashboard.php");
}

if(isset($_GET['logout']))
{
 session_destroy();
 unset($_SESSION['userSession']);
 header("Location: index.php");
}
?>

That’s all, we have covered here a user Registration and Login Script with PHP and MySQLi please do share it with your friends

  1. There is an error in your doc, config.php should be dbconnect.php.

    Thanks for the article.

  2. Hi John Thank You for knowing me, I have fixed the error and you can give a database connection file name what you want, but you have to use only your database connection file name at all time config.php it’s only for example

    Thank You

  3. This is really attention-grabbing, You are an excessively skilled blogger.

    I have joined your feed and look ahead to seeking more of your magnificent post.
    Additionally, I’ve shared your website in my social networks!

Leave a Reply