User Registration and Login Script with PHP and MySQL | Coding Cage

User Registration and Login Script with PHP and MySQL

By
In this tutorial we will discuss how to create user registration and login management system with PHP and MySQL in simple procedural way. user registration and login system is most important thing for any kind of web applications and it is common thing too, and session plays important role in this type of system, for that we have to use session, In this tutorial, we are going to use PHP sessions to keep user login status, see the live demo of php mysql login signup script or you can also download this script, and i have updated this script with php server side validations, so how to do login php let’s start.
User Registration and Login Script with PHP and MySQL
 

read also : Login and Registration with PDO and OOP
read also : Login Script with Email Verification & Forgot Password using PHP
read also : Login and Registration with PHP MySQLi

First of all create a database and table as below.
you can create it by importing following sql command in to your phpmyadmin.
database : dbtest
table : users

--
-- Database: `dbtest`
--

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

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `userId` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(30) NOT NULL,
  `userEmail` varchar(60) NOT NULL,
  `userPass` varchar(255) NOT NULL,
  PRIMARY KEY (`userId`),
  UNIQUE KEY `userEmail` (`userEmail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
copy-paste the above sql code into phpmyqdmin to create database and table.

Now we have to create following files..
–dbconnect.php
–register.php
–index.php
–home.php
–logout.php





dbconnect.php

contains code for localhost connection and database selection.

<?php

 // this will avoid mysql_connect() deprecation error.
 error_reporting( ~E_DEPRECATED & ~E_NOTICE );
 // but I strongly suggest you to use PDO or MySQLi.
 
 define('DBHOST', 'localhost');
 define('DBUSER', 'root');
 define('DBPASS', '');
 define('DBNAME', 'dbtest');
 
 $conn = mysql_connect(DBHOST,DBUSER,DBPASS);
 $dbcon = mysql_select_db(DBNAME);
 
 if ( !$conn ) {
  die("Connection failed : " . mysql_error());
 }
 
 if ( !$dbcon ) {
  die("Database Connection failed : " . mysql_error());
 }


NOTE : we have to start session in all the pages.
>> I have used here simple HTML5 required attribute to validate the following register and login forms.
if you want to know more about validations click here : validations

register.php

contains simple html form and few lines of php code.
save this file as ‘register.php‘, this file contains simple html form with all the required registration fields except user id because it’s auto incremented and some php code for registering a new user. all the user registration process can be done in this single php file.

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

 $error = false;

 if ( isset($_POST['btn-signup']) ) {
  
  // clean user inputs to prevent sql injections
  $name = trim($_POST['name']);
  $name = strip_tags($name);
  $name = htmlspecialchars($name);
  
  $email = trim($_POST['email']);
  $email = strip_tags($email);
  $email = htmlspecialchars($email);
  
  $pass = trim($_POST['pass']);
  $pass = strip_tags($pass);
  $pass = htmlspecialchars($pass);
  
  // basic name validation
  if (empty($name)) {
   $error = true;
   $nameError = "Please enter your full name.";
  } else if (strlen($name) < 3) {
   $error = true;
   $nameError = "Name must have atleat 3 characters.";
  } else if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
   $error = true;
   $nameError = "Name must contain alphabets and space.";
  }
  
  //basic email validation
  if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
   $error = true;
   $emailError = "Please enter valid email address.";
  } else {
   // check email exist or not
   $query = "SELECT userEmail FROM users WHERE userEmail='$email'";
   $result = mysql_query($query);
   $count = mysql_num_rows($result);
   if($count!=0){
    $error = true;
    $emailError = "Provided Email is already in use.";
   }
  }
  // password validation
  if (empty($pass)){
   $error = true;
   $passError = "Please enter password.";
  } else if(strlen($pass) < 6) {
   $error = true;
   $passError = "Password must have atleast 6 characters.";
  }
  
  // password encrypt using SHA256();
  $password = hash('sha256', $pass);
  
  // if there's no error, continue to signup
  if( !$error ) {
   
   $query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')";
   $res = mysql_query($query);
    
   if ($res) {
    $errTyp = "success";
    $errMSG = "Successfully registered, you may login now";
    unset($name);
    unset($email);
    unset($pass);
   } else {
    $errTyp = "danger";
    $errMSG = "Something went wrong, try again later..."; 
   } 
    
  }
  
  
 }
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"  />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>

<div class="container">

 <div id="login-form">
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
    
     <div class="col-md-12">
        
         <div class="form-group">
             <h2 class="">Sign Up.</h2>
            </div>
        
         <div class="form-group">
             <hr />
            </div>
            
            <?php
   if ( isset($errMSG) ) {
    
    ?>
    <div class="form-group">
             <div class="alert alert-<?php echo ($errTyp=="success") ? "success" : $errTyp; ?>">
    <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
                </div>
             </div>
                <?php
   }
   ?>
            
            <div class="form-group">
             <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
             <input type="text" name="name" class="form-control" placeholder="Enter Name" maxlength="50" value="<?php echo $name ?>" />
                </div>
                <span class="text-danger"><?php echo $nameError; ?></span>
            </div>
            
            <div class="form-group">
             <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
             <input type="email" name="email" class="form-control" placeholder="Enter Your Email" maxlength="40" value="<?php echo $email ?>" />
                </div>
                <span class="text-danger"><?php echo $emailError; ?></span>
            </div>
            
            <div class="form-group">
             <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
             <input type="password" name="pass" class="form-control" placeholder="Enter Password" maxlength="15" />
                </div>
                <span class="text-danger"><?php echo $passError; ?></span>
            </div>
            
            <div class="form-group">
             <hr />
            </div>
            
            <div class="form-group">
             <button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button>
            </div>
            
            <div class="form-group">
             <hr />
            </div>
            
            <div class="form-group">
             <a href="index.php">Sign in Here...</a>
            </div>
        
        </div>
   
    </form>
    </div> 

</div>

</body>
</html>
<?php ob_end_flush(); ?>


Now, after creating registration page, then move ahead to create login page.
i’ve written this login script with little bit security to prevent your website from sql injection.

index.php/login page

this file also contains html form with two input box which will take user email and user password entered by user and then after submitting the form, the php code will match that user email and password combination in database and when it finds both results in table then it will start a session and allow user to access home page else it will show appropriate message.

<?php
 ob_start();
 session_start();
 require_once 'dbconnect.php';
 
 // it will never let you open index(login) page if session is set
 if ( isset($_SESSION['user'])!="" ) {
  header("Location: home.php");
  exit;
 }
 
 $error = false;
 
 if( isset($_POST['btn-login']) ) { 
  
  // prevent sql injections/ clear user invalid inputs
  $email = trim($_POST['email']);
  $email = strip_tags($email);
  $email = htmlspecialchars($email);
  
  $pass = trim($_POST['pass']);
  $pass = strip_tags($pass);
  $pass = htmlspecialchars($pass);
  // prevent sql injections / clear user invalid inputs
  
  if(empty($email)){
   $error = true;
   $emailError = "Please enter your email address.";
  } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
   $error = true;
   $emailError = "Please enter valid email address.";
  }
  
  if(empty($pass)){
   $error = true;
   $passError = "Please enter your password.";
  }
  
  // if there's no error, continue to login
  if (!$error) {
   
   $password = hash('sha256', $pass); // password hashing using SHA256
  
   $res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
   $row=mysql_fetch_array($res);
   $count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
   
   if( $count == 1 && $row['userPass']==$password ) {
    $_SESSION['user'] = $row['userId'];
    header("Location: home.php");
   } else {
    $errMSG = "Incorrect Credentials, Try again...";
   }
    
  }
  
 }
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"  />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>

<div class="container">

 <div id="login-form">
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
    
     <div class="col-md-12">
        
         <div class="form-group">
             <h2 class="">Sign In.</h2>
            </div>
        
         <div class="form-group">
             <hr />
            </div>
            
            <?php
   if ( isset($errMSG) ) {
    
    ?>
    <div class="form-group">
             <div class="alert alert-danger">
    <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
                </div>
             </div>
                <?php
   }
   ?>
            
            <div class="form-group">
             <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
             <input type="email" name="email" class="form-control" placeholder="Your Email" value="<?php echo $email; ?>" maxlength="40" />
                </div>
                <span class="text-danger"><?php echo $emailError; ?></span>
            </div>
            
            <div class="form-group">
             <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
             <input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" />
                </div>
                <span class="text-danger"><?php echo $passError; ?></span>
            </div>
            
            <div class="form-group">
             <hr />
            </div>
            
            <div class="form-group">
             <button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
            </div>
            
            <div class="form-group">
             <hr />
            </div>
            
            <div class="form-group">
             <a href="register.php">Sign Up Here...</a>
            </div>
        
        </div>
   
    </form>
    </div> 

</div>

</body>
</html>
<?php ob_end_flush(); ?>


after registration page and login page we need to create ‘home‘ page which shows users dashboard, which is authentic page and this page cannot access without logging in.

home.php

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
 ob_start();
 session_start();
 require_once 'dbconnect.php';
 
 // if session is not set this will redirect to login page
 if( !isset($_SESSION['user']) ) {
  header("Location: index.php");
  exit;
 }
 // select loggedin users detail
 $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
 $userRow=mysql_fetch_array($res);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['userEmail']; ?></title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css"  />
<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="https://codingcage.com/2015/01/user-registration-and-login-script-using-php-mysql.html">Back to Article</a></li>
            <li><a href="https://codingcage.com/search/label/jQuery">jQuery</a></li>
            <li><a href="https://codingcage.com/search/label/PHP">PHP</a></li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
            
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
     <span class="glyphicon glyphicon-user"></span>&nbsp;Hi' <?php echo $userRow['userEmail']; ?>&nbsp;<span class="caret"></span></a>
              <ul class="dropdown-menu">
                <li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li>
              </ul>
            </li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav> 

 <div id="wrapper">

 <div class="container">
    
     <div class="page-header">
     <h3>Coding Cage - Programming Blog</h3>
     </div>
        
        <div class="row">
        <div class="col-lg-12">
        <h1>Focuses on PHP, MySQL, Ajax, jQuery, Web Design and more...</h1>
        </div>
        </div>
    
    </div>
    
    </div>
    
    <script src="assets/jquery-1.11.3-jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    
</body>
</html>
<?php ob_end_flush(); ?>


logout.php

this page contains only few lines of php code to unset and destroy the current logged in users session, and after destroying the session the page automatically redirect to the ‘index/login’ page.

<?php
 session_start();
 if (!isset($_SESSION['user'])) {
  header("Location: index.php");
 } else if(isset($_SESSION['user'])!="") {
  header("Location: home.php");
 }
 
 if (isset($_GET['logout'])) {
  unset($_SESSION['user']);
  session_unset();
  session_destroy();
  header("Location: index.php");
  exit;
 }

I hope this article helped you to learn php mysql login with signup. If you have any feedback please let me know by using comment or If you have any query or any doubt then please feel free to ask.



393 comments:

  1. thanx for the nice thing...

    ReplyDelete
    Replies
    1. First at all, I really appreciated for this great tutorials, I am beginner to PHP, now i set up my own website so I was trying to create members...... I want only members can access the main home page....
      For this tutorials , I created all the files, everything is coming pretty but I am facing issue on home.php

      Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/home.php on line 10

      Delete
    2. please check your mysql table fields with the mysql select query in home.php at line 9

      Delete
    3. Thanks for the script..Me too getting the same error please help

      Delete
    4. hello amruthesh
      please check your mysql table fields with the mysql select query in home.php at line 9 which is as follow

      $res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
      $userRow=mysql_fetch_array($res);

      Delete
    5. Really good stuff!! Thanks!

      Delete
    6. mysql is not working anymore, try with mysqli

      Delete
    7. try with mysqli, mysql don't work anymore on 5.5

      Delete
    8. mysql is not working anymore, try with mysqli

      Delete
    9. thanks very much for this script , check out more @ www.q-demos.com

      Delete
    10. Good work although procedures such as mysql_query should be replaced by the newer more secure ones mysqli_query ... etc.

      Delete
  2. thanx for this script...
    but where's the zip file..

    ReplyDelete
  3. very nice...

    ReplyDelete
  4. very nice one ..really to much helpful..

    ReplyDelete
  5. If you want another easy way to create login,logout and register system using php and mysql,please proceed to=>>
    http://merounicsathi.blogspot.com/2015/03/if-u-r-searchinghow-to-create_18.html

    ReplyDelete
  6. Really helpful for beginners...

    ReplyDelete
  7. Nice but can we have it converted to Mysqli

    ReplyDelete
  8. I've had a few problems with this code, specifically the registration and log-in pages. When I hit submit on the registration page after filling out the form, I keep getting a message that there was an error and that registration failed.

    I decided to test the log-on page, and created some records in the DB (using PHPmyadmin) and then using this information to log in. Again I got an error that I could not log-in, despite the log-in information being correct.

    Any ideas what the problem is here? It seems to a problem with connecting to the DB.

    ReplyDelete
    Replies
    1. download the zip file i've update it with correction...

      Delete
    2. Download link is above at the end of the tutorial ...

      Delete
  9. Everything else is working except for Login. It is inserting values while registration, but not fetching it while login. Please help.

    ReplyDelete
    Replies
    1. this is working script ,
      check your login credentials with exact database values.

      Delete
  10. Hi,
    how can you protect multiple pages apart from the index.php?
    does the session apply to any file in the same directory (or sub directories) or does the in the head of the index.php need to be included in every file that i want protected?
    thanks.

    ReplyDelete
    Replies
    1. yes by defining a session you can protect the pages you want...

      Delete
    2. sir please upload dashboard report tutorials such as graphical charts or bars. I am your solid followers on your blogs.

      Delete
    3. try following

      http://www.chartphp.com/how-to-create-dashboard-php-mysql/
      http://webdesign.tutsplus.com/tutorials/build-a-dynamic-dashboard-with-chartjs--webdesign-14363
      https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxchart/jquery-chart-getting-started.htm

      Delete
  11. Pradeep you're a star. I can confirm that the coding works, thank you very much. I just added a registration and login system to a website that's part of my portfolio as a junior Webmaster!!

    ReplyDelete
    Replies
    1. thanks thomas for kind words,
      and i would recommend you to use PDO or MySQLi, this tutorial was just for beginners.

      Delete
  12. Hi there! Works great except error shows when not logged in (but error gone when logged in):

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home2/server/public_html/login/index.php on line 5

    Thanks and help appreciated.

    ReplyDelete
    Replies
    1. Hi David,
      if you modified the script then check again MySQL Select Query on Index page which selects user email with exact table name and fields.

      Delete
    2. sir my problem is when i click sign me up, it keeps on showing "error while registering you"
      i've tried like 10 times with different username, email and password but ther result is always like that

      Delete
    3. hello dontiax,
      please check mysql insert query on register.php , or check users table fields with insert query values.

      mysql_query("INSERT INTO users(username,email,password) VALUES('$uname','$email','$upass');

      Delete
  13. Thanks man ... It is very simple ... Thanks please update more tutorial like this ... Thanks again

    ReplyDelete
  14. Hi sir,
    i need a help from you.The homepage code above is the only page for all the users.Im currently doing a project.Im doing a clinic system.In my system,i have three users doctor,staff and patients.Therefore,i need three different homepage for three different users.Im using the same code above.Could you edit code above and get me the solution,sir.

    ReplyDelete
    Replies
    1. Hi Dineas,

      Yes above home page code is for all users and as you have three types of users in your system , for that you have to create role based login system so , give roles to the users and create three pages for users,
      alter your table and add role field then in login code fetch user role and redirect them to specific page.
      and please use PDO or MySQLi.

      Delete
    2. Sir,i need a help from you.I'm new to php.I need you to edit your codes above for doctor's registration.The data's to insert into database are doctor id,name,specialistin,qualification,email,password and contact no.I also need different pages for three types of doctors.Please help sir and your help would be much appreciated.Please send the codes here.

      Delete
  15. Script not redirecting. I even changed the Location from home.php

    ReplyDelete
  16. Access denied for user 'root'@'localhost' (using password: NO) how can i fix this? please?

    ReplyDelete
  17. Getting the same error Access denied for user 'root'@'localhost' (using password: NO) not sure what to check as far as the MySQL username...

    ReplyDelete
    Replies
    1. it seems you have a password for root user then provide password ...

      Delete
  18. is this script secure? i mean pw can't be stolen somehow?

    ReplyDelete
    Replies
    1. this script is just for beginners, you can make your password more secure by using some hashing functions which are introduced

      password hashing functions
      Login and Registration with PDO and OOP

      Delete
  19. Thanks for the information Pradeep, u really really really help me a lot, for building my website company.
    the script is is really working for localhost web.
    but after i import the mysql database, the web can not read it.

    Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'@'localhost' (using password: NO) in /home/dabdtmfo/public_html/dbconnect.php on line 2
    oops connection problem ! --> Access denied for user 'root'@'localhost' (using password: NO)

    Please help me Sir. Thanks

    ReplyDelete
    Replies
    1. if you used this script on online server then you must provide your server details like "username" or "password" replace them in mysql_connect("server_name","username","your _password");

      and please don't use MySQL extensions it is deprecated, use MySQLi or PDO

      here is the same script using PDO : Login & Registration Script with PDO and OOP

      Delete
  20. hello mate your script so awesome but I'm having a problem which is I dont undertood everything was working but once i test to login I'm having an error which is "The request sent by your browser was not understood." I don't know what is that mean.

    I have to create an account again and after like 24 hours this error would appear, why is that? I'm not a back-end developer. Thanks mate.

    ReplyDelete
    Replies
    1. that's browsers request error, try to googling about it and code is working...

      Delete
  21. Problem with sign in Please help

    ReplyDelete
    Replies
    1. what kind of problem you are facing in this script ...?

      Delete
    2. Same thing on me. I registered successfully but i can't logged in. it says error details.

      Delete
  22. Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\signup\index.php on line 15

    ReplyDelete
  23. Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\signup\index.php on line 15

    ReplyDelete
  24. hi,please am having challenges with error.please can you help out please?
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\signup\index.php on line 15

    ReplyDelete
    Replies
    1. Hi Adebayo,
      if you modified the script then check again MySQL Select Query on Index page which selects user email with exact table name and fields.

      Delete
  25. Can you add email confirmation on this form?

    ReplyDelete
  26. it works .. thank you so much ..

    ReplyDelete
  27. Hei. I use your script but I have a big problem..I create an account ..and i've tried to connect..when I press the button "SIGN IN" nothing happens..but right after if i press the text.."Sign Up Here" than..he logging me on home.php..what can I do to solve this problem? Thanks a lot for your support.

    ReplyDelete
    Replies
    1. Hi Omar....

      Make sure you have put the "header("Location: home.php")" function on login button click
      like this :

      if(isset($_POST['btn-login']))
      {
      $email = mysql_real_escape_string($_POST['email']);
      $upass = mysql_real_escape_string($_POST['pass']);
      $res=mysql_query("SELECT * FROM users WHERE email='$email'");
      $row=mysql_fetch_array($res);

      if($row['password']==md5($upass))
      {
      $_SESSION['user'] = $row['user_id'];
      header("Location: home.php");
      }
      else
      {
      echo "wrong details !!!";
      }

      }

      hence this is working script...

      hope this helps :)

      Delete
    2. i have same problem and i just did as code you post here, but still when I press the button "SIGN IN" nothing happens..but right after if i press the text.."Sign Up Here" than..he logging me on home.php..

      Delete
    3. Hi Omar, I have same problem, just wondering how did you fix it. plz.
      when I press the button "SIGN IN" nothing happens..but right after if i press the text.."Sign Up Here" than..he logging me on home.php..

      Delete
  28. Thank you so much, amazing tutorial :)

    ReplyDelete
  29. How to secure that script against SQL Injection attacks?

    ReplyDelete
  30. Don't work for me. if(!mysql_connect("localhost","aiva..._db...","d7...."))

    Can;t understand that line. of course, i tryed to chmod it to 777 and i typed password and everything correctly.

    " Access denied for user 'aiva..._db...'@'localhost' (using password: YES) "

    i can't really where is the problem? sql file already injected.

    ReplyDelete
    Replies
    1. try this

      $host = "localhost";
      $username = "root";
      $password = "your_password";
      $dbname = "database_name";

      mysql_connect("$host","$username","$password");
      mysql_select_db($dbname);

      and don't use MySQL extension, you can use PDO or MySQLi

      Delete
  31. sir. i am new to php. i have a small doubt. i have already created a server and tried your sample CRUD operations with php and mysql. Now i am trying to execute this program, for that i want to use the same server. should i create a new table so that this program will execute

    ReplyDelete
    Replies
    1. Hi Manoj,

      yes you have to create another table for user registrations and login, crud tutorial has "users" table name change the table name as you want and create another table for users, so that you may have two tables
      first is for crud, second is for users..

      Delete
    2. thank you sir. i have done it sir but now i am facing a new problem...while i am trying to register it is saying..
      Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\manu\regstn\index.php on line 14.
      i have checked the line but i am unable find what is the error..please guide me sir..

      Delete
    3. Hi Manoj
      if you created new table then check your table name or it fields in both files register.php and index.php, there's must be a mismatch in mysql select query in "index.php"

      check this : $res=mysql_query("SELECT * FROM users WHERE email='$email'");

      Delete
    4. hi sir..
      i want the script for 'search' operation sir..where can i find it sir...

      Delete
    5. i'll post a tutorial about searching with php mysql soon :)

      Delete
  32. Hi,
    i'm still new in php . currently doing my final year project.
    thank you for the good tutorial.
    but i don't understand how can i relate this tutorial with my website ?
    i really appreciate if you can help me. thank you ^^

    ReplyDelete
    Replies
    1. Hello Yangg,
      it's easy to implement this script , this was just a login and registration module , if you have users or admin panel there you can put this script.

      but please don't use MySQL extension it's now deprecated use either PDO or MySQLi
      following are the same scripts which may help you, these are using PDO with OOP concept

      Login Registration with Email Verification & Forgot Password
      Login Registration with New Password Hashing Functions


      for MySQLi : https://codingcage.com/search/label/MySQLi
      for PDO : https://codingcage.com/search/label/PDO
      for PHP OOP : https://codingcage.com/search/label/PHP OOP

      Delete
  33. thnx for it. may god help u more then u r helping others

    ReplyDelete
  34. Very nice! thanks so much.....love you

    ReplyDelete
  35. wheres zip file// id always DL in rar!

    ReplyDelete
  36. Bro i have a problem. I successfully registered but when i login it says wrong details. I checked my database table and look for my e-mail and pass but still it puts me into else statement which is wrong details. Help bro

    ReplyDelete
    Replies
    1. hello gino, i have used here md5() password hashing function, so please check it. or by mistake you actually giving wrong details, please check again your login details with exact database table values

      Delete
  37. hi sir
    i am having a problem with signing up, everytime i click sign me up, it keeps on showing "error while registering you"
    i've already tried different username, password, and name but it does have the same result .

    ReplyDelete
    Replies
    1. hello dontiax,
      please check mysql insert query on register.php , or check users table fields with insert query values.

      mysql_query("INSERT INTO users(username,email,password) VALUES('$uname','$email','$upass');

      there's must be a mismatch on users table , so please again check properly

      Delete
  38. i need to create a admin panel so that users can update the website easily. can i use this with your php crud tutorial? Or why not create a complete crud tutorial with admin panel? please....

    ReplyDelete
  39. how to redirect after successful registeration

    ReplyDelete
    Replies
    1. hello karthick,
      on which page you want to redirect after registration, is it login page or home page ?

      Delete
  40. Great php tutorials tips for programming. It can help better for website developers.Thanks for this useful post.

    ReplyDelete
  41. makek money now with your link try https://victly.com mini cashout 10$ per 1000 views in USA

    ReplyDelete
  42. Awesome stuff !! We have also created an easy to use and advance script for user registration and management system in PHP http://www.infotuts.com/user-registration-management-script-php/. Hope you guys will like this script.

    ReplyDelete
  43. I keep getting a pop up of 'wrong details' before the page presents the login css....I may have things inserted backwards, but I have
    script('wrong details');script


    just before the

    in my login page....is there something I may have wrong? Seems like it's doing the check for the login credentials before I action inserting the credentials in the username and password location of the login..any help with proper placement would help...thanks

    Scott

    ReplyDelete
    Replies
    1. hello scott,
      make sure that you are inserting right credentials while login, try to register a new user and login that user, it works, or if you modified or change this script then please check again with this actual code with your code, if it is possible to send me your code via email , i will get back to you surely with the working code :)

      Delete
  44. Look my Tutorial:

    - https://www.youtube.com/watch?v=6Fd_2rkOuqM

    Subscribe!

    ReplyDelete
  45. thanks a lot this is what i,ve looking for
    thanks for sharing

    ReplyDelete
    Replies
    1. you're welcome Aliyandi :)

      Delete
    2. Hi....Mr.Pradeep sir

      i am new to php....i have followed your instruction above codes but i am getting this error sir please give a solution tip for my error

      Error i am getting is ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\Login form\dbconnect.php on line 2
      Call Stack
      # Time Memory Function Location
      1 0.0010 244312 {main}( ) ..\index.php:0
      2 0.0010 248080 include_once( 'C:\wamp\www\Login form\dbconnect.php' ) ..\index.php:3
      3 0.0010 248408 mysql_connect ( ) ..\dbconnect.php:2

      Delete
    3. hello bharath,
      you are getting this error because you are using higher version of php and this tutorial uses mysql extension, mysql is now deprecated,

      paste the following error reporting code in "dbconnect.php" just above mysql_connect();

      error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );

      but i recommend you to use PDO or MySQLi here is the same script using PDO

      Login Registration using PDO

      Email Verification and Forgot Password Script using PDO


      Delete
  46. Hi....Mr.Pradeep sir

    i am new to php....i have followed your instruction above codes but i am getting this error sir please give a solution tip for my error

    Error i am getting is ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\Login form\dbconnect.php on line 2
    Call Stack
    # Time Memory Function Location
    1 0.0010 244312 {main}( ) ..\index.php:0
    2 0.0010 248080 include_once( 'C:\wamp\www\Login form\dbconnect.php' ) ..\index.php:3
    3 0.0010 248408 mysql_connect ( ) ..\dbconnect.php:2

    ReplyDelete
  47. Hi....Mr.Pradeep sir

    i am new to php....i have followed your instruction above codes but i am getting this error sir please give a solution tip for my error

    Error i am getting is ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\Login form\dbconnect.php on line 2
    Call Stack
    # Time Memory Function Location
    1 0.0010 244312 {main}( ) ..\index.php:0
    2 0.0010 248080 include_once( 'C:\wamp\www\Login form\dbconnect.php' ) ..\index.php:3
    3 0.0010 248408 mysql_connect ( ) ..\dbconnect.php:2

    ReplyDelete
  48. Adding extra pages that will give access to members. How is that done? Plus is there a way to add roles to members?

    ReplyDelete
    Replies
    1. hello chriz, yes you can add extra pages for members access only, just create the pages you want and add session code

      session_start();
      include_once 'dbconnect.php';

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

      it will give access only logged in members, and i will post role based login system soon on this blog :)

      Delete
  49. Please tell how to add a upload option for individual for uploading file

    ReplyDelete
    Replies
    1. hey shar, please let me know, which file you want to upload for individual user is it user profile pic or any other ?

      Delete
  50. i am not being able to redirect it to home page after login.

    ReplyDelete
    Replies
    1. hello kavish, please check there if any error or exception occurs or not, if it is then show me the error, ? or check redirection code

      Delete
    2. i dont have any errors but i still cant redirect it to home.php.

      Delete
    3. hi, i unable to redirect to home.php after i successfully registered and log in. Dont have any errors too.

      Delete
    4. Hello Asyraf, check redirection code = header("Location: home.php"); or you might have some other problem ,please check.your code

      Delete
    5. Hello sir and thanks for the amazing tutorial, you are really great!! I face exactly the same problem as asyram and although i have the redirection code correct I am not able to redirect to home.php. I used mysqli your other tutorial. Any ideas?

      Delete
    6. Hello anni, please make sure that you have used header function properly.

      Delete
  51. thank you sir, i was able to find my error.

    ReplyDelete
  52. Thanks for the share this helped me a lot :)

    ReplyDelete
  53. why my dbconnect cannot work
    '.mysql_error());
    }
    if(!mysql_select_db("db_payment"))
    {
    die('oops database selection problem ! --> '.mysql_error());
    }
    ?>

    ReplyDelete
    Replies
    1. please check again your database name in mysql_select() function with your database in phpMyAdmin

      Delete
  54. This is a great code! However, when i tried to register 2 accounts with the same credentials (username,password and email) it allows me to create 2 accounts with the same credentials. How to avoid making it happen? 2 accounts with the same credentials? Help me please.
    Thanks in advance!

    ReplyDelete
  55. Hello! Amazing code right there~
    However, i discovered an error wherein i tried to register 2 accounts with the same credentials (username, password, and email), and it allows me to create the same cred. How to prevent this to happen?
    Thank you and have a nice day!

    ReplyDelete
    Replies
    1. Hi there, this is just for newbies, you can try following
      Login Registration with PHP PDO MySQL using OOP

      to prevent duplicate entries , first of all you need to select user email id from mysql table while registering and if email already exists then print message that email is already taken

      Delete
  56. Sir why your demo and source code are not same? in your demo only login form but your source code their are registration form

    ReplyDelete
    Replies
    1. hello there, actually i have given the both login and signup for demo, but to avoid fake registrations which are used just for demos and i got more than hundred records daily in my db for demo, that's why i have removed signup part from the demo :)

      Delete
  57. hello, I'm newbie in php. I like your tutorial and your source code is easier to understand, But one think i'm consider, is every time I run this, will increase number of connection to mysql. is it ok? coz if let say 100 persons connect it will be jammed the connection to mysql. how to solve this?

    ReplyDelete
  58. Hello,

    I have a problem with this code. It connects fine and registers users as it is supposed to! so that's great! However, I keep getting the alert "wrong details" every time I try to login with one of the registered email and password combo. Do you have any suggestions?

    Greetings

    ReplyDelete
    Replies
    1. Hi Jelle , please make sure you entering the correct details, or check in mysql database that the email or password exists or not.

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

    ReplyDelete
  60. Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/u320103427/public_html/dbconnect.php on line 2

    Warning: mysql_connect(): Access denied for user 'root'@'10.2.1.48' (using password: NO) in /home/u320103427/public_html/dbconnect.php on line 2
    oops connection problem ! --> Access denied for user 'root'@'10.2.1.48' (using password: NO)

    can you help me ??

    ReplyDelete
    Replies
    1. hello there,
      use the following code just above mysql connection code within "dbconnect.php"

      error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );

      and if you have password for your server then provide password in mysql_connect function

      mysql_connect("localhost","root","PASSWORD_HERE")

      Delete
  61. I get this error - Notice: Undefined variable: row in C:\xampp\htdocs\index.php on line 14

    ReplyDelete
  62. Hi, thank you for amazing code you have here. I did copy the zip and follow what ever you said, i can connect to MyPhpAdmin and see the login and registration form, but when i try to register new user give this warning:

    Error while registering you…

    ReplyDelete
    Replies
    1. Hello Iraj, please make sure that you have created table properly as i used in this tutorial, copy and paste the sql code to create table and try to register new user.

      Delete
    2. thank you i fix the table and work now but when I press the button "SIGN IN" nothing happens..but right after if i press the text.."Sign Up Here" than..he logging me on home.php..what can I do to solve this problem? Thanks a lot for your support. also here the code i use index.php file:

      Delete
    3. Hello Iraj, did made any changes in this script ?
      check in index.php within button login condition this

      if($row['password']==md5($upass))
      {
      $_SESSION['user'] = $row['user_id'];
      header("Location: home.php");
      }

      Delete
    4. Hello, yes i have exactly same code on index.php but same problem.!

      here my php code on Inex page:

      Delete
    5. Hi, No i didn't change anything, i have same script on my index.php

      Delete
  63. Hi! Thanks to your tutorial I'm finally having progress, so thank very much for it, but... Every time I run the code this:

    "( ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\icchihanatest\login-registration-system\login-registration-system\dbconnect.php on line 2
    Call Stack
    # Time Memory Function Location
    1 0.0020 134968 {main}( ) ..\home.php:0
    2 0.0030 137704 include_once( 'C:\wamp\www\icchihanatest\login-registration-system\login-registration-system\dbconnect.php' ) ..\home.php:3
    3 0.0030 137896 mysql_connect ( ) ..\dbconnect.php:2"

    appears, I knew to coding, so... I don't know much about it. You already did an awesome work with this and, once again, thank you very much and I am sorry if I'm already asking too much. But, you're help will be more than welcome.

    ReplyDelete
  64. Hello! Thanks <3
    But there is a little problem...
    If I try to register someone or login,it doesn't work :( why?

    ReplyDelete
    Replies
    1. Hello Alessia, if it's not work with you then there's must be some misconfiguration with your code, so please check your code again, if it displaying error then show me error.

      Delete
  65. Hey dude it worked efficiently but how should i redirect it after user signup and then how should i display user name on the top right side.Furnish me the details as early as possible , i hope you don't mind if i share this with my project working teams who are creating applications for final year BCA projects. Really this could help us a lot. I am searching for this type of coding but i couldn't find even in youtube. Thanks a lot.

    ReplyDelete
  66. A Simple but complete tutorial. Thanks Pradeep. Works perfectly

    ReplyDelete
    Replies
    1. you're welcome deij,
      thanks for visiting :)

      Delete
  67. I have a question about the Logout.php portion, the second part of the IF statement seems redundant to me.

    else if(isset($_SESSION['user']) != "")

    You have an unset check as the first condition, so it will only move on if $_SESSION is set, why wouldn't you leave the second condition as ($_SESSION != "")? Seems redundant to repeat the set check. However i can understand the set and not empty check in one line

    ReplyDelete
    Replies
    1. Hi there, the first condition will never let you open "logout.php" if the user is not logged in. and the second else condition, if user is logged in he cannot open "logout.php" so in the both condition user cannot open logout.php page directly. it will work silently for destroying session.

      Delete
  68. First of all I want to thank you for a great full script.

    Now I want to help you by hearing the process where user can change there current password.

    ReplyDelete
    Replies
    1. Hello Ibrahim,
      this is easy, if you have created a profile page for particular user then take a three text box for password, first one is for current password and the other two are for new password, confirm password and within change password button condition execute a update sql query

      Delete
    2. can you make it for me? please

      Delete
  69. I hope you guys are not using this on a production server, 1. You are using deprecated MySQL syntax instead of MySQLi or PDO, 2. MD5 is a bad password hashing algorithm (refer stackoverflow), 3. no strong sanitization 4. no secure session 5. no brute force protection and there are many more.

    ReplyDelete
    Replies
    1. Hello XOQ, go through all the tutorial, i have covered those tutorials also, there are Login Signup using PDO and MySQLi with OOP concept as well with new password hashing functions

      Delete
    2. and yes you are right, we can't use deprecated MySQL version on production server, well this tutorial was just for beginners and i also recommend users to use MySQLi or PDO

      Delete
  70. Thanx for your web site..and it is very helpful for us....thanx boss

    ReplyDelete
    Replies
    1. You're welcome Nahid
      Keep Visiting... :)

      Delete
  71. When i first registered the task was completed succesfully but afterwards when i try to register again with different id it says error while registering you, even in your rar file. Can u help me ?

    ReplyDelete
    Replies
    1. Hello Ayush Kumar, sorry for the late reply, did you solved this error ? if not then let me know ...

      Delete
  72. Thanks bro!!! this was helpful! but when I see the members and their info in phpmyadmin, there, the passwords are hashed in md5. i want to remove this feature. pls help me

    ReplyDelete
    Replies
    1. Hello BlackHacker, just remove the md5() function from the script within(index.php and register.php).

      Delete
  73. When i registered first time it was done correctly but later on when i tried to register a new id again it showed error again and again even when i run your zip file. Can u please help me ?

    ReplyDelete
  74. Hey man. do you have another download link for the rar? it won't let me download it from box

    ReplyDelete
    Replies
    1. Hello Jay, Download this script again from dropbox...

      Delete
  75. YES!!! YOU'RE THE MAN!!! THANK YOU!!! I'll follow your PDO tutorial next :D since this one is deprecated.

    ReplyDelete
    Replies
    1. Hello Shahin, yes it's deprecated. use PDO or MySQLi(PDO recommended)
      and thanks for visiting :)

      Delete
  76. Thanks for the code, but for me it dosen't work. Can you please tell what can be the possible error?

    ReplyDelete
    Replies
    1. Hi Waqar, how can i tell you the possible error, there may be lot's of, and how can i predict any one, well this is working script i have given here, so if there some error then show me the error, i may try to solve the particular one ...

      Delete
  77. Thanks a lot, it works great! I have one question. With these sessions only registered users can access to all inserted data. How to create that every registered user will access only to his own inserted data ?

    ReplyDelete
  78. I tried to implement it in seesharp.ravikandel.com.np but it doesnot worked properly.
    lets check there

    ReplyDelete
    Replies
    1. Hello Ravi, i have checked your site, login and registration works so what's the problem, if you have another issue do let me know ...

      Delete
  79. I get this types of errors on all pages ? Can you tell me what could be the cause?
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\tester\index.php on line 19

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\tester\index.php on line 21

    ReplyDelete
    Replies
    1. Hello Bogdan
      please check your query with exact database table fields on 'index.php' or show me the query so that i can help you...

      Delete
  80. Hii! I have some problems here. When I want to open my folder on apache server I always have some errors. As I see problem is in some file. I also try with you downloaded script. Please, could you help me? :)

    ReplyDelete
    Replies
    1. Hello Amar, what kind of errors you are facing , let me know ?

      Delete
  81. Hi,

    The registration works well, however the login doesn't. To prove this I removed the md5# from the source code and the table so I can test properly. I have tried every possible way to try and make it work. Screenshots below.

    After registering: https://gyazo.com/b9dffa8524917d54000586d6ece30282
    Changed the password type to text to prove this: https://gyazo.com/6f0bcbf6fdedbeec43260bec17e8fb52
    https://gyazo.com/07b30442fcf1c3927a6e6629ed127f5a

    Please give me a solution to this, thanks.

    ReplyDelete
  82. thx but I got a problem,
    when I tryed to login and it never worked so I checked phpmyadmin and in the registered user, all got the same password, it wasn't the one I set for the register, it was d41d8cd98f00b204e9800998ecf8427e for all my try can you explain me why and may solve my problem pls ?

    ReplyDelete
  83. where do i have 2 put the codes?? in dreamweaver ??

    ReplyDelete
  84. hello sir.. thank you so much for that.. it works... but my problem is how to insert voting area? because my system was an online election... ugh... i really dont know... pls help me... thanks...

    ReplyDelete
  85. thank you sir... it works.. but i want to make an online election, how to continue making it? please help me... thanks

    ReplyDelete
  86. Anyone know how to make a PHP store???

    ReplyDelete
  87. Can I Request To? Please Make Me A Simple Online Examination with Login and Registration of user and admin ... i will pay it...

    ReplyDelete
  88. nice tutorial... suposing i don't want multiple login using same login details.. is there a way you can help me.. i have a program (voting system) i have developed.. that seem to be hte only thing left

    ReplyDelete
  89. i put your exact code on my server and can't login, it simply says wrong details, I have tried creating another test user to no success. any help is appreciated. Thanks

    ReplyDelete
  90. http://gbpg.in/user/register.php showing error while registation
    Hi Pradeep,
    I tried to implement it in http://gbpg.in/user/ but it doesnot worked properly.
    lets check there

    ReplyDelete
    Replies
    1. hello ajay, please make sure that you have create table properly or check mysql queries with exact table fields...

      Delete
  91. Thanks very much for this, but i am having this error " Warning: mysql_fetch_array() expects parameter 1 to be resource, object given in C:\wamp\www\IT Project\bootstrap\home.php on line 10"

    this is what i edited cuz i had a different table
    Home.php---->
    "$res=$mysqli->query("SELECT * FROM user WHERE userid=".$_SESSION['user']);
    $userRow=mysql_fetch_array($res)"

    index.php--->
    "$res = $mysqli->query("SELECT * FROM user WHERE email='$email'");
    $row = mysqli_fetch_array($res);"

    register.php--->
    " if($mysqli->query("INSERT INTO user(firstname, email, password, userlevel) VALUES('$fname','$email','$upass','2')"))"

    i don't seem to find any error in the query

    ReplyDelete
  92. i got error like this
    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\lr\register.php on line 23

    ReplyDelete
  93. sir i m getting this error
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in F:\xampp\htdocs\login-registration-system\login-registration-system\index.php on line 19
    when i sign up
    and when i login to my account (which i ve created by manually entering data to db)
    i got this error
    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in F:\xampp\htdocs\login-registration-system\login-registration-system\index.php on line 21


    what should i do?

    ReplyDelete
    Replies
    1. Hello Jyotirman Adarsh, did you make some changes in this script ?
      if yes then please check the mysql insert and select queries on index page with exact database table fields.

      Delete
  94. Don't work, cause it doesn't work. I don't understand

    CREATE DATABASE `dbtest` ;
    CREATE TABLE `dbtest`.`users` (
    `user_id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `username` VARCHAR( 25 ) NOT NULL ,
    `email` VARCHAR( 35 ) NOT NULL ,
    `password` VARCHAR( 50 ) NOT NULL ,
    UNIQUE (`email`)
    ) ENGINE = MYISAM ;

    And I have not enough permissions. PLease help

    ReplyDelete