Simple Login and Signup System using PHP and MySQLi | Coding Cage

Simple Login and Signup System using PHP and MySQLi

By
hello friends, we already have this tutorial but using MySQL extension but that's deprecated now and some users want it using MySQLi extension, so i have decided to post 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, Login script with MySQL so let's take a look.
Simple Login and Signup System with PHP and MySQLi


Database Design

the database used in this tutorial is "dbtest" and the table is users, so create dbtest in your phpmyadmin and paste the following sql code to create users table.

--
-- Database: `mysqli_login`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_users`
--

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(60) NOT NULL,
  `email` varchar(60) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

dbconnect.php

this file contains code for connection using MySQLi extension, here's how you can use MySQLi an improved extension with your MySQL Database.

<?php

  $DBhost = "localhost";
  $DBuser = "root";
  $DBpass = "";
  $DBname = "mysqli_login";
  
  $DBcon = new MySQLi($DBhost,$DBuser,$DBpass,$DBname);
    
     if ($DBcon->connect_errno) {
         die("ERROR : -> ".$DBcon->connect_error);
     }

register.php

this is our registration/signup page for the new user and 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); it will make password stronger than MD5.

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

if(isset($_POST['btn-signup'])) {
 
 $uname = strip_tags($_POST['username']);
 $email = strip_tags($_POST['email']);
 $upass = strip_tags($_POST['password']);
 
 $uname = $DBcon->real_escape_string($uname);
 $email = $DBcon->real_escape_string($email);
 $upass = $DBcon->real_escape_string($upass);
 
 $hashed_password = password_hash($upass, PASSWORD_DEFAULT); // this function works only in PHP 5.5 or latest version
 
 $check_email = $DBcon->query("SELECT email FROM tbl_users WHERE email='$email'");
 $count=$check_email->num_rows;
 
 if ($count==0) {
  
  $query = "INSERT INTO tbl_users(username,email,password) VALUES('$uname','$email','$hashed_password')";

  if ($DBcon->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>";
   
 }
 
 $DBcon->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;
  }
  ?>
          
        <div class="form-group">
        <input type="text" class="form-control" placeholder="Username" name="username" required  />
        </div>
        
        <div class="form-group">
        <input type="email" class="form-control" placeholder="Email address" name="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 is our login page which will ask users to enter email and password to go the home page which is members page, to use database we have to include "dbconnect.php" file. i have used here password_verify($upass, $row['password']) to verify password this is new password hashing functin and you have to use PHP5.5 to use this function.

<?php
session_start();
require_once 'dbconnect.php';

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

if (isset($_POST['btn-login'])) {
 
 $email = strip_tags($_POST['email']);
 $password = strip_tags($_POST['password']);
 
 $email = $DBcon->real_escape_string($email);
 $password = $DBcon->real_escape_string($password);
 
 $query = $DBcon->query("SELECT user_id, email, password FROM tbl_users WHERE email='$email'");
 $row=$query->fetch_array();
 
 $count = $query->num_rows; // if email/password are correct returns must be 1 row
 
 if (password_verify($password, $row['password']) && $count==1) {
  $_SESSION['userSession'] = $row['user_id'];
  header("Location: home.php");
 } else {
  $msg = "<div class='alert alert-danger'>
     <span class='glyphicon glyphicon-info-sign'></span> &nbsp; Invalid Username or Password !
    </div>";
 }
 $DBcon->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="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>

home.php

if user successfully logged in he will be redirected to this "home.php" page, this is members page only registered users can access this page, contains bootstrap header with menu and one link to logout.

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

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

$query = $DBcon->query("SELECT * FROM tbl_users WHERE user_id=".$_SESSION['userSession']);
$userRow=$query->fetch_array();
$DBcon->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.codingcage.com">Coding Cage</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="http://www.codingcage.com/2015/03/simple-login-and-signup-system-with-php.html">Back to Article</a></li>
            <li><a href="http://www.codingcage.com/search/label/jQuery">jQuery</a></li>
            <li><a href="http://www.codingcage.com/search/label/PHP">PHP</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.codingcage.com/">Coding Cage - Programming Blog</a><br /><br />
    <p>Tutorials on PHP, MySQL, Ajax, jQuery, Web Design and more...</p>
</div>

</body>
</html>

logout.php

simple page to logout the users and 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: home.php");
}

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

That's it, we have covered here a simple login and registration system using PHP and MySQLi, the reason behind posting this tutorial is, i got few emails regarding MySQLi login and signup script, so i have posted it here. if you like it please share it with your social media friends, thank you :)



63 comments:

  1. this is the error i am getting when i try to register
    Fatal error: Call to a member function real_escape_string() on a non-object in

    ReplyDelete
    Replies
    1. Hello there, hope it's not too late to reply, download this script again :)

      Delete
  2. Need access to the bootstrap files. Unable to download the entire script.

    ReplyDelete
    Replies
    1. Hello Shravan, download the script again...

      Delete
  3. When i want register i get this error
    Notice: Undefined variable: MySQLi_CON in D:\skola\PRJ\XAMP\htdocs\myshop\registration.php on line 18

    Fatal error: Call to a member function real_escape_string() on a non-object in D:\skola\PRJ\XAMP\htdocs\myshop\registration.php on line 18

    ReplyDelete
    Replies
    1. Hello there, did you solved it, if not then download it again :)

      Delete
  4. I registered successfully but when I try to log in ,I can see <>. Can you help me? Thanks.

    ReplyDelete
    Replies
    1. Hello Ivan , get this script again download and try it...

      Delete
  5. am getting an Fatal error: Call to undefined function password_hash() in C:\xampp\htdocs\ehis\Register.Php on line 15 on the register.php page

    ReplyDelete
  6. on the register.php replace $new_password = password_hash($upass, PASSWORD_DEFAULT); on line 15 with $new_password = md5($upass);
    also on the index.php replace if(password_verify($upass, $row['password'])) on line 19 with if(md5($upass, $row['password']))

    ReplyDelete
  7. how to put this codes?? in dreamveaver?

    ReplyDelete
  8. when i can find ...all the script ..without problems ?

    ReplyDelete
  9. hi, i have an error in register.php.
    when i want to register another account, it said error while registering.
    is it have problem with the if($count==0)?
    because when i manually increase the user_id in database from 0 to 1 or 2(not 0), then it will display successfully registered.
    please, Help me. :(

    ReplyDelete
  10. Works perfectly great tutorial...
    Do you happen to have a form like this but have a separate user and admin login ?
    Thanks

    ReplyDelete
  11. Nice tutorial...
    Do you happen to have a form where the user and the admin can log-in and redirects on different pages? Thanks

    ReplyDelete
    Replies
    1. Hello Mark, you mean role based login(admin, user) ok i will make tutorial for this topic, keep visiting :)

      Delete
    2. Hi Pradeep !, Please do a small script to separate admin and user please? I need this script for this...

      Thanks

      Delete
    3. Hello Prozic,
      if i got time i will surely post tutorial about it

      Delete
  12. Your day is gone there is still error
    datbase wont add any user no sucessful message shown when add new member
    there is some serious logical mistake in this code
    i m gone
    wasted my time here

    ReplyDelete
    Replies
    1. Hello Lytron,
      sorry for the trouble with your code, please make sure you have created database table properly and comply with this code, or please try to echo insert query while signing up, you may there get your error.

      Delete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Hello, i realli like this script! I need to have it so that only users that have the "activated" value of 1 can view the home.php. Users who are not yet been activated will see a different page. Can you please implement this in the script or paste a line here that will make this work? Thank you in advance.

    ReplyDelete
  15. hello, i can register successfully, and username and password is saved in database, but when i try to login after registering, it says "email or password does not exists !" can you plz help

    ReplyDelete
  16. Hello... How can i remove the hashing in it as i have to add my own encryption method.
    Thank you. Urgent!

    ReplyDelete
  17. How do you set up style sheet again with this new script with style sheet?

    ReplyDelete
  18. Hi, how do you style the login script again as like you did with the old code you publish?

    ReplyDelete
  19. Worked for me! I just had to adjust the password to connect to phpMyAdmin on the dbconnect.php file. Thanks for the helpful code! I really appreciated this after looking for almost a week for something like this.

    ReplyDelete
  20. this is work success in wampserver 2.5
    if anybody want to make this script sucessfully without any error you must download wampserver 2.5 .

    ReplyDelete
  21. how to run the downloaded file?

    ReplyDelete
    Replies
    1. hello there, just download the code and put in your www directory then open the path in your , that's it ..

      Delete
  22. Replies
    1. Hello Pranav, Now you can download the code, please go and download it..
      thanks ...

      Delete
  23. im not able to download this...

    ReplyDelete
    Replies
    1. Hi Girish, now you can download the code..

      Delete
  24. Hi Pradeep,

    I am getting this error 'Notice: Trying to get property of non-object' in line '$count=$check_email->num_rows;'
    Any idea?

    ReplyDelete
  25. i cant even download this fiole. please send me the link on my email cefriandysimarmata@gmail.com

    ReplyDelete
    Replies
    1. Hello Gilang, now you can download the code, please go and get it...

      Delete
  26. yesterday, i was subscribed your site but until i still can't download, can you send me the link to my email dirgaenggar@gmail.com

    ReplyDelete
  27. I become an error:
    Fatal error: Call to undefined function password_verify() in C:\xampp\htdocs\index.php on line 23

    Can you help me?Thanks!

    ReplyDelete
  28. i cant download the script even i have subscribed

    ReplyDelete
  29. cant download the code i am subscribed but when i press download it says that im not subscribed then i click subscribe now and in the popup windows it says im already subscribed

    ReplyDelete
    Replies
    1. Hello Kyouma, now you can download the code....

      Delete
  30. Want a material design login and register page, then check out here
    https://17chapters.blogspot.in/2016/08/how-to-make-login-and-register-system.html

    It's just awesome

    ReplyDelete
  31. can i ask how do i make a profile page for the registered account they can update their info like name, age, gender, etc.

    ReplyDelete
  32. Hi can you do a profile page that they can edit their names, ages, address, etc. i tried changing the register.php to just retrieve the data but when i change the select to update it wont do anything. thanks in-advance

    ReplyDelete
  33. Thanks Bro for a great tutorial.. it was very easy to understand and practice it. Thanks!

    ReplyDelete
  34. Can I just say, it works (almost) out of the box for me and that's amazing! I was getting ready to put hours and hours into this to make it work, but it's so easy!
    Thank you so much!

    ReplyDelete
  35. Me too has been looking a long time for something like this. I like it - and it works, which is important. My problem is that I am not able to change from being directed to home.php after I have log in. In your earlier version and on xampp it worked with replacing home.php but not live with this version. Only get a blank page. I am a newbie and of course lack of knowledge.

    ReplyDelete
  36. Mysqli -> checked
    oop -> checked
    escape string -> checked
    prepared statements -> FAILED

    You can't only trust to escape strings. You must use prepared statements on your every sql connection. Even things like user login system, it's a must. Without prepared statements no one should use this codes.

    But thanks anyway, it rare to find login codes with new 5.5 functions.

    ReplyDelete
  37. Ever had the problem where when logging in or registering it takes you to a blank page?

    ReplyDelete
  38. Hi there,
    Really appreciate the script, very helpful for beginners! However, I'm having an issue that I'm hoping you can help me with.

    The script is working fine, but when I try to "sign up" I am not redirected to any pages, and the new user isn't visible in the MySQL database table. I've opened the developer tools inside chrome to try and get a better look, and I'm not getting any console log errors. However, when I open up the network section I get the message "failed to load response data".

    I would greatly appreciate any help you can give me.
    Jay,

    ReplyDelete
  39. how can you view the users created in your database

    ReplyDelete
  40. how can you view the ussers created in your database

    ReplyDelete
  41. In the Sign In page, it says "invalid username or password" but the form asks for email and password. Moreover, when I create an account and log in afterwards, it always says 'invalid usersame or password" What could be the error here? Thanks

    ReplyDelete
  42. In the Sign In page, it says "invalid username or password" but the form asks for email and password. Moreover, when I create an account and log in afterwards, it always says 'invalid usersame or password" What could be the error here? Thanks

    ReplyDelete
  43. It works perfectly!

    Thank you very much for sharing your knowledge. I have never seen such easy-to-understand and usefull tutorial for php programing.

    Again, Thanks a lot,
    Best

    ReplyDelete
  44. Hello. I have the same problem. When i "sign up" i am not redirected to any page. It just resets the email and password and it stays on same page.

    ReplyDelete