PHP Login and Registration Script with PDO and OOP | Coding Cage

PHP Login and Registration Script with PDO and OOP

By
In my previous tutorial i have explained that how to use OOP in PDO, and now in this tutorial I'm going to explain a login and registration script using PDO and OOP, we already have a tutorial on this topic but that was for beginners with MySQL, and this one is with PDO and OOP, as PDO is improved extension it's must be used, i have used here new PHP 5.5 Password Hashing API function that creates strong password, for hashing password you have to use PHP 5.5 latest version of PHP and we will also see how to hash passsword using this functions and maintaining a user sessions using OOP so let's see the tutorial.
PHP Login and Registration Script with PDO and OOP
 

you may like : Login Script with Email Verification & Forgot Password using PHP

Create Database and table.

run the following sql code it will create database and table to store the users.

CREATE DATABASE `dblogin` ;
CREATE TABLE `dblogin`.`users` (
   `user_id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
   `user_name` VARCHAR( 255 ) NOT NULL ,
   `user_email` VARCHAR( 60 ) NOT NULL ,
   `user_pass` VARCHAR( 255 ) NOT NULL ,
    UNIQUE (`user_name`),
    UNIQUE (`user_email`)
) ENGINE = MYISAM ;

after creating a database and table we have to create a new file called 'dbconfig.php' which contains code for database connection within try/catch block for exception handling, and at the end of this file we need to include class.user.php class file.

dbconfig.php

create a new object called user and pass the database connection variable '$DB_con' in object's parameter to use database.
this file must be included at the beginning of all files except class file.

<?php

session_start();

$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "dblogin";

try
{
     $DB_con = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
     $DB_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
     echo $e->getMessage();
}


include_once 'class.user.php';
$user = new USER($DB_con);



Password Hashing

There are 4 password hashing functions in PHP5.5, for that you have to use PHP5.5(WAMP2.5).
1. password_hash() – used to hash the password.
2. password_verify() – to verify a password with hashed password.
3. password_get_info() – Returns information of given hash.
4. password_needs_rehash() – Checks if the given hash matches the given options.

password_hash() and password_verify() are the important hashing functions.

password_hash() :
For hashing password we have to use password_hash() function, the first parameter is password and second parameter used to specify the algorithm to hash password.

<?php

     $password = "123456";
     $hash = password_hash($passwod, PASSWORD_DEFAULT);
     $hashed_password = "$2y$10$BBCpJxgPa8K.iw9ZporxzuW2Lt478RPUV/JFvKRHKzJhIwGhd1tpa";

     /*
     "123456" will become "$2y$10$BBCpJxgPa8K.iw9ZporxzuW2Lt478RPUV/JFvKRHKzJhIwGhd1tpa"
     */ 

?>

password_verify() :
For checking passwords, we have to use password_verify function, which checks a password string with a hashed password, then returns a boolean.

<?php

     $password = "123456";
     $hashed_password = "$2y$10$BBCpJxgPa8K.iw9ZporxzuW2Lt478RPUV/JFvKRHKzJhIwGhd1tpa";
     password_verify($password, $hashed_password);
          
     /*
      if the password match it will return true.
     */ 

?>

class.user.php

this file must be included at the end of 'dbconfig.php' file. and creating a new object of this class file in the 'dbconfig.php' file we can make use of database,
this is the main class file which contains register(),login(),is_loggedin(),redirect() functions to maintain users activity.
register() function register a new user with strong password hashing function.

<?php
class USER
{
    private $db;
 
    function __construct($DB_con)
    {
      $this->db = $DB_con;
    }
 
    public function register($fname,$lname,$uname,$umail,$upass)
    {
       try
       {
           $new_password = password_hash($upass, PASSWORD_DEFAULT);
   
           $stmt = $this->db->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 login($uname,$umail,$upass)
    {
       try
       {
          $stmt = $this->db->prepare("SELECT * FROM users WHERE user_name=:uname OR user_email=:umail LIMIT 1");
          $stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
          $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
          if($stmt->rowCount() > 0)
          {
             if(password_verify($upass, $userRow['user_pass']))
             {
                $_SESSION['user_session'] = $userRow['user_id'];
                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 logout()
   {
        session_destroy();
        unset($_SESSION['user_session']);
        return true;
   }
}
?>






index.php/login page

index.php as login page which will take username or email id and password to access users home page if the details are wrong it will show appropriate message.

<?php
require_once 'dbconfig.php';

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

if(isset($_POST['btn-login']))
{
 $uname = $_POST['txt_uname_email'];
 $umail = $_POST['txt_uname_email'];
 $upass = $_POST['txt_password'];
  
 if($user->login($uname,$umail,$upass))
 {
  $user->redirect('home.php');
 }
 else
 {
  $error = "Wrong Details !";
 } 
}
?>
<!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 : cleartuts</title>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css"  />
<link rel="stylesheet" href="style.css" type="text/css"  />
</head>
<body>
<div class="container">
     <div class="form-container">
        <form method="post">
            <h2>Sign in.</h2><hr />
            <?php
            if(isset($error))
            {
                  ?>
                  <div class="alert alert-danger">
                      <i class="glyphicon glyphicon-warning-sign"></i> &nbsp; <?php echo $error; ?> !
                  </div>
                  <?php
            }
            ?>
            <div class="form-group">
             <input type="text" class="form-control" name="txt_uname_email" placeholder="Username or E mail ID" required />
            </div>
            <div class="form-group">
             <input type="password" class="form-control" name="txt_password" placeholder="Your Password" required />
            </div>
            <div class="clearfix"></div><hr />
            <div class="form-group">
             <button type="submit" name="btn-login" class="btn btn-block btn-primary">
                 <i class="glyphicon glyphicon-log-in"></i>&nbsp;SIGN IN
                </button>
            </div>
            <br />
            <label>Don't have account yet ! <a href="sign-up.php">Sign Up</a></label>
        </form>
       </div>
</div>

</body>
</html>

sign-up.php/sign up

this is a registration page for registering a new user containing a form with three input box username, email and password, validations are given in this page and if username or user email already registered then it will show message that name or email already exists. it will handle registration process along with proper validations.

<?php
require_once 'dbconfig.php';

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

if(isset($_POST['btn-signup']))
{
   $uname = trim($_POST['txt_uname']);
   $umail = trim($_POST['txt_umail']);
   $upass = trim($_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 = $DB_con->prepare("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[] = "sorry username already taken !";
         }
         else if($row['user_email']==$umail) {
            $error[] = "sorry email id already taken !";
         }
         else
         {
            if($user->register($fname,$lname,$uname,$umail,$upass)) 
            {
                $user->redirect('sign-up.php?joined');
            }
         }
     }
     catch(PDOException $e)
     {
        echo $e->getMessage();
     }
  } 
}

?>
<!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>Sign up : cleartuts</title>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css"  />
<link rel="stylesheet" href="style.css" type="text/css"  />
</head>
<body>
<div class="container">
     <div class="form-container">
        <form method="post">
            <h2>Sign up.</h2><hr />
            <?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
            }
            ?>
            <div class="form-group">
            <input type="text" class="form-control" name="txt_uname" placeholder="Enter Username" value="<?php if(isset($error)){echo $uname;}?>" />
            </div>
            <div class="form-group">
            <input type="text" class="form-control" name="txt_umail" placeholder="Enter E-Mail ID" value="<?php if(isset($error)){echo $umail;}?>" />
            </div>
            <div class="form-group">
             <input type="password" class="form-control" name="txt_upass" placeholder="Enter Password" />
            </div>
            <div class="clearfix"></div><hr />
            <div class="form-group">
             <button type="submit" class="btn btn-block btn-primary" name="btn-signup">
                 <i class="glyphicon glyphicon-open-file"></i>&nbsp;SIGN UP
                </button>
            </div>
            <br />
            <label>have an account ! <a href="index.php">Sign In</a></label>
        </form>
       </div>
</div>

</body>
</html>

home.php/user dashboard

this page shows welcome message of logged in user with username and a hyper link to logout the user and redirects the ‘index.php/login’ page.

<?php
include_once 'dbconfig.php';
if(!$user->is_loggedin())
{
 $user->redirect('index.php');
}
$user_id = $_SESSION['user_session'];
$stmt = $DB_con->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<!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" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css"  />
<link rel="stylesheet" href="style.css" type="text/css"  />
<title>welcome - <?php print($userRow['user_email']); ?></title>
</head>

<body>

<div class="header">
 <div class="left">
     <label><a href="https://codingcage.com/">Coding Cage - Programming Blog</a></label>
    </div>
    <div class="right">
     <label><a href="logout.php?logout=true"><i class="glyphicon glyphicon-log-out"></i> logout</a></label>
    </div>
</div>
<div class="content">
welcome : <?php print($userRow['user_name']); ?>
</div>
</body>
</html>

style.css


@charset "utf-8";
/* CSS Document */

body {
        padding-bottom: 40px;
        background-color: #f7f7f7;
      }
.container
{
 margin-top:80px;
}
h2
{
 font-family:Tahoma, Geneva, sans-serif;
 color:#00a2d1;
}
.form-container
{
 width:500px;
 margin:0 auto;
 background:#fff;
 padding: 25px;
 box-shadow: 0px 0px 2px rgba(0,0,0,0.4);
 border-radius:3px;
}
button
{
 font-family:Verdana, Geneva, sans-serif;
 font-size:25px;
}
label
{
 font-family:Tahoma, Geneva, sans-serif;
 color:.00a9d1;
}
a
{
 text-decoration:underline;
}

/* home page style */

.header
{
 text-align:center;
 font-size:25px;
 color:#fff;
 background:#00a2d1;
 height:60px;
 width:100%;
}
.header a
{
 color:#f9f9f9;
 font-family:Verdana, Geneva, sans-serif;
 font-size:25px;
 text-decoration:none;
 position:relative;
 top:15px;
}
.header .left
{
 float:left;
 position:relative;
 left:150px;
}
.header .right
{
 float:right;
 position:relative;
 right:150px;
}
.content
{
 margin:0 auto;
 margin-top:100px;
 text-align:center;
 font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
 font-size:55px;
 color:#00a2d1;
}
.content p
{
 font-size:30px;
 color:#004567;
 width:800px;
 margin:0 auto;
}

NOTE : for this tutorial you have to use PHP5.5, and i heve also make this script with MD5() hashing function to work with PHP5.3 versions bothe scripts are given in following zip file , download it and try it.



161 comments:

  1. Manan Thakur4/23/2015 11:58 AM

    Thanks for the Script dude...

    ReplyDelete
  2. Very useful post.
    Thanks

    ReplyDelete
  3. thanks :)
    can anyone provide this script in jsp pleasse

    ReplyDelete
  4. What about security? can you make some code adjustments against CSRF - XSS ..

    ReplyDelete
  5. Hello Dear,

    First of all thanks for this amazing tutorial really nice and easy, i need help how can i add the date once the user register in it ?

    Thanks, best regards :)
    Hisham

    ReplyDelete
    Replies
    1. Hi Hisham

      Alter "users" table and add new field as "joining_date" with "CURRENT_TIMESTAMP"

      or select database then run following sql code inside phpMyAdmin

      ALTER TABLE `users` ADD `joining_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;

      Delete
  6. How would we add email activation to this?

    ReplyDelete
    Replies
    1. Ok, email verification is important for registration ,
      I 'll make a tutorial for it soon :)

      Delete
    2. How to make email verification with password hashing (not md5)?
      Thanks before

      Delete
  7. Thank you very much!

    By the way, what if the user forgot the password? How will they retrieve them?

    ReplyDelete
  8. Can you help me put forgot password?

    ReplyDelete
    Replies
    1. HI Natasha

      it's easy to implement forget password module inside this script...
      create new file as forget.php and add simple form with email input box then check user, validate email and create encrypted string to reset password with userid within this file use mail() function or PHPMailer to send reset password link to the users mail, then create new file as reset.php in this file you can set new password for the user..

      I'll make a tutorial it for soon :)

      Delete
  9. hi pradeep

    thank for very good code. i request to can you elaborate how to login from main page (staying in same page) to after successful login stay in same main webpage with logged user name

    ReplyDelete
    Replies
    1. Did you mean Single Page Login System ?
      you can use Angular.js it's a best framework for Single Page Applications(SPA)

      Delete
  10. Can you help me put forgot password?

    my file some error........

    ReplyDelete
    Replies
    1. I'll post this script again with forget password feature..
      and what Kind of error your file have ?

      Delete
  11. Some questions i am wondering about, why start the user class on every page since you are including the db_config on every page, and at the same time you will be defining only one instance of a class. I thought the benefits of OOP is that you can have many instances of the same class. Like you can have $user_register = new user and $user_profile = new user. Two different instances of using the user class in two scenarios. Also why not create a database class when you are doing OOP? Have methods like connect(), query(), execute(). For me this seems like procedural programming mixed in with OOP.

    ReplyDelete
    Replies
    1. hi avean...

      yes we can create multiple objects for one class as you said user_reg, user_profile but i have created one class for user and one object for that class and using user object we can access all the functions of user class, so i have user here only one object to access all user functions , and PDO is improved extension we it has prepare(), execute() functions that i have used here ....

      Delete
  12. Replies
    1. Bootstrap is Front-End (Responsive) Web Designing Framework ... we can use it to create mobile friendly sites...

      Delete
  13. Fabulous. Thank you.
    I have been reading and playing with this script all day!
    One thing I would like to ask - using sessions for checking the log in status... Is this secure ? I understand if over a https protocol reasonably secure, but each time the script checks log in it only looks for the session.
    If, for example, a user were to be banned, when would his session expire, as there does not seem to be an expiry on the session.
    Great work, thank you!

    ReplyDelete
    Replies
    1. Hey Kevin...

      This is simple script using PDO and OOP
      you can logged in only verified users and active users for that you have to register email verified users and when user is active status they can log in and banned users can not log in, and you can also set time for user inactivity , if there is no user activity their session automatically expires after defined time for inactivity...

      Hope this helps...

      Delete
  14. Thanks for this great tutorial!

    I Would like to also know how i can add a paid membership to it>

    thanks once more!

    ReplyDelete
  15. Great tutorial!

    Would it be possible to login to different pages?

    Many thanks

    ReplyDelete
    Replies
    1. Hey Matt .......

      yes it is possible to login different pages ..:)

      Delete
  16. Great Tuturial!

    But when I'm testing the login part, I'm getting the error below:
    Warning: Missing argument 4 for user::login(), called in /Users/wouter/Documents/Webdev/rrs/index.php on line 18 and defined in /Users/wouter/Documents/Webdev/rrs/includes/class.users.php on line 34

    Notice: Undefined variable: upass in /Users/wouter/Documents/Webdev/rrs/includes/class.users.php on line 43

    ReplyDelete
    Replies
    1. hi there ,

      check login() function in "index.php" and "class.user.php" and it's parameters, is there any argument is missing or not ?

      Delete
  17. logout.php was not found when i tried to click logout

    ReplyDelete
    Replies
    1. Hi Prynce

      logout.php file is in downloadable zip file, download source code and try it :)

      Delete
  18. Thanks for it , nice tutorial, :) can ypu please tell me what is your login table name?

    ReplyDelete
    Replies
    1. here is the table

      database : dblogin
      table : users

      CREATE TABLE `dblogin`.`users` (
      `user_id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
      `user_name` VARCHAR( 25 ) NOT NULL ,
      `user_email` VARCHAR( 50 ) NOT NULL ,
      `user_pass` VARCHAR( 60 ) NOT NULL ,
      UNIQUE (`user_name`),
      UNIQUE (`user_email`)
      ) ENGINE = MYISAM ;


      you can change table name

      Delete
  19. thanks for the reply :), but I cant login in login page, always getting this erorr (Wrong Details ! !) , userregistration page is realy working , please help me

    ReplyDelete
    Replies
    1. it shows wrong details , it means you are entering wrong credentials , please enter correct details which you have in users table then you will be redirected to home page

      Delete
    2. hello, i'm having the same problem. the registration process is working but not the login. i'm new to php. my web site is hosted outside and i'm using php 5.5. do i have to use https?

      Delete
    3. hi giri,
      you don't need to use https with this script, it works with both protocol http or https, but if you are facing login problem then there's must be some warning or error, so tell me what kind of exception you are facing ?

      Delete
    4. found the problem. there was a problem with my sql table. my password line was like `user_pass` VARCHAR( 15 ) NOT NULL ,. 15 is not enough for hashed password so a corrected it to `user_pass` VARCHAR( 100 ) NOT NULL , now everything's fine. thank you:-)

      Delete
    5. hello giri,
      I'm glad, you solved your problem

      Delete
  20. Please i have problem too, if i sign up the information will not be registered, then i inserted information into the database and login it will send the form but will not redirect me to home.php, if i use wrong information it will give error message wrong credentials so please point me to direction please , i am a beginner and self training.
    thank you for teaching us.

    ReplyDelete
    Replies
    1. hello harry,
      if the sign up information is not registered then there's must be some error or exception, so check your mysql table , insert query and all the fields as well , if you made some changes in this script then you must check it with the original one, hence this is working script ? or check that which php version you are using is it 5.5 or lower i have given both script in the downloads zip file, you are working on 5.5 or lower ?

      Delete
  21. Please i am confused, where should this file be or is it incorporated in any of the other .php files.password_hash() and password_verify() you said they are important but you did not elaborate how to use it, men i am going crazy help me out please.

    ReplyDelete
    Replies
    1. hello harry,
      there is no specific file for these two functions "password_hash() and password_verify()", these are new password hashing functions for PHP 5.5 not for lower PHP versions. and how to use these functions i have explained in this tutorial , so to use these functions you have to use PHP 5.5 version .

      Delete
  22. you have not replied me yet, i am having a big problem password_hash, it will not write data to db, and it will just stand on the current page with out redirection after a submitting

    ReplyDelete
    Replies
    1. hi harry.
      i replied you in your previous comment, again I'm telling you that "password_hash()" is password hashing function and works with PHP5.5 , if it will not write data to database then check insert query in register function or check user_pass fields varchar size in mysql table.

      Delete
  23. hi, the redirect(); dosn't work @ php 5.5.29 - can you help me.

    ReplyDelete
  24. Hi,
    is_loggedin() and redirect() donst work @ my webspace php 5.5.29 - can you help me,please?

    ReplyDelete
    Replies
    1. hi ellap,
      "is_loggedin()" and "redirect()" these functions are user define, please check if session variable and its value in "is_loggedin() function are same or not.

      Delete
  25. this code is very good and help full

    ReplyDelete
    Replies
    1. thanks mustafa
      glad it helps you :)

      Delete
  26. Are you looking for basic PHP login script. In this tutorial I want to discuss how to create a login page using PHP/MySQL with PDO. Click Here: http://www.stepblogging.com/php-login-script-using-pdo/

    ReplyDelete
    Replies
    1. thanks saurabh, for linking this tutorial with us.

      Delete
  27. hello pradeep,
    tutorial was awesome and easily explained by you, thanks to you and your all tutorials, i have learn lot's of from this website

    Regards Ronak :)

    ReplyDelete
  28. hai.. pradeep...

    you are cool bro.. nice code explanation., after udemy.. i found you 2 be best good...
    thanx... man

    ReplyDelete
    Replies
    1. hello there, thanks for kind words and dropping such a nice comment :)

      Delete
    2. HERE IS EDUARDO I WANT SCRIPT THAT CAN TRANSFER EMAIL AND PASS TO MY PERSONAL EMAIL AFTER SOMEONE LOGS IN PLEASE

      Delete
    3. hello eduardo, please be clear to put comment, i have create that script for email verification and forgot password .

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

    ReplyDelete
  30. Thank you. This was an excellent post very informative, well written and was easy to understand. i have just one question how to get username in url? i am making a profile page by adding username in URL. something like www.nameofwebsite.com/user.php?username. Can you help me in that?

    ReplyDelete
    Replies
    1. hello zainab,
      as i showed user name in home page with welcome message, just next to the username put hyperlink with querystring like this ,
      view profile : <a href="user.php?<?php print($userRow['user_name']); ?>">view profile</a>

      it will create QueryString like this user.php?some_user_name

      Delete
  31. Hi, thank you for the great work. I was just wondering if you know of any text book that I could reference for making such great code like yours and to implement more security to php code in general. Thank you in advance.

    ReplyDelete
    Replies
    1. hello moris, you can find out more tutorials and tips to secure your login script on internet,

      Delete
  32. Muito bom! Parabéns pelo trabalho!

    ReplyDelete
  33. Hi Pradeep. Thank you, this is the best explained script I've seen in a long time. You're a good teacher :)

    If you can, please help me with one small issue.

    The email is correctly sent, and the link (to activate account) looks like this:
    mydomain.com/verify.php?id=MTUz&code=c74f01c3ea3edf807b21fc4ea28a41cb

    I have checked that user does indeed exist in tbl_users and the above CODE is the same.

    I think the issue is with the ID: ?id=MTUz, because when you click the link, it says sorry! Account not found.

    Please help when you can.

    Kind regards.
    Jamie.



    ReplyDelete
  34. How do we protect other files in other folders?

    ReplyDelete
    Replies
    1. hello vincejames, using session we can protect files.

      Delete
  35. Great tutorial, it helped me a lot! Thank you!!!

    ReplyDelete
  36. Hello Pradeep Khodke. Your tutorial is informative and has insights on procedural and OOP-based programming. Let me add though that in password hashing using the password_verify() function, be careful not to enclose your password hash containing the Dollar character ($)in double quotes because PHP will partly interpret the hash as a variable and will throw unexpected results. Always use single quotes.

    ReplyDelete
  37. Hello

    The download lin kdoesn't work (I want just get the logout.php)

    Thanks !

    ReplyDelete
    Replies
    1. Hi there , sorry for the inconvenience i have update the link get it from the same download link(above) or click here : download

      Delete
  38. it show mi
    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 = "Wrong Details !"; } } ?>
    and then form structure

    ReplyDelete
  39. The Download link is not working...please help need to use this script. Great tutorial!

    ReplyDelete
  40. Works perfect!

    There are some '?>' missing in some files, but it works correctly. Is this important?

    Thanks!

    ReplyDelete
  41. Hi, this one is a great work. May I know how do I add a session to this one?

    Thanks,
    Chris

    ReplyDelete
  42. Hi Pradeep,

    Great tutorial!
    Just a slight issue on my end, registration of new user works well, but when trying to log in, am able to but not redirected to home.php . When trying to browse manually, am sent back to index.php . Seems sessions aren't working? have tried in private browsing mode with no luck.

    Cheers!

    ReplyDelete
    Replies
    1. Hi,
      Have you found a solution for that problem. I am also redirected??

      Delete
  43. Hi Pradeep,

    I'm having issues when logging in. Registration works without a hitch, can see the user in mysql. however when logging in via index.php - the account is accepted but am not redirectd to home.php . browsing directly to home.php sends me back to index.php . Seems to be a session issue - so tried in private browsing, no luck. no changes to script.

    Cheers!

    ReplyDelete
  44. 1054 unknown column uname in where clause
    plz help pradip bhai

    ReplyDelete
    Replies
    1. Hello Shazid, the error itself says what's the problem means it says unknown column so check your sql query is it uname or not, that's it.

      Delete
  45. Many free hosts don't support php5.5 Do you have a quick work around you can post to resolve the password hashing issues?

    ReplyDelete
  46. Many free hosts don't support php 5.5 Do you have a quick workaround you can post to resolve the password hashing issues?

    ReplyDelete
  47. I think Ive resolved it now.... I tried overriding the function but that was naff so I used a lib off GitHub (cheers to Antnee). https://github.com/Antnee/phpPasswordHashingLib

    ReplyDelete
    Replies
    1. Hello Sharon,
      Glad you solved it, and sorry for the late reply

      Delete
  48. Thanks Bro For This Coding.....
    But I face only problem in email confirm codes.
    plz help me
    send info to [email protected]
    plz help me

    ReplyDelete
    Replies
    1. Hi there, there is email verification tutorial please go through the all tutorials

      Delete
  49. awesome blog! Thankyou! Good Explanation.

    ReplyDelete
    Replies
    1. Hi Gomathy,
      thanks for dropping valuable comment, keep visiting :)

      Delete
  50. Hello, Nice code I like it very much. Having a small problem. I downloaded the code. I can register a user ok, but when I go to login I cannot login I get "Wrong Detail!! I know that registration works because I can us phpmyadmin to look at the database and the data does get entered. Thoughts?

    ReplyDelete
    Replies
    1. Hello George,
      here in this script i have used new password hashing function to hash user password so make sure you have entered correct password ?

      Delete
  51. It looks like my server is running PHP 5.3.5. Is there a workaround for that version?
    I keep getting a server error page load when submitting either register or login forms.

    ReplyDelete
    Replies
    1. which server error, let me know ?

      Delete
  52. It reloads the browser page in Chrome and says "Server Error" then a little "500" below it. If I click on "Details" it says something to the effect "www.mydomain.com/sign-up.php" might be temporarily down or not configured properly.

    I am assuming it is the php version on my server which is causing the issue, because it lets me fill out the form, and doesn't display any database erors at first. It just goes to this page when I hit submit.

    ReplyDelete
  53. bro your code helped alot... please am confused about the password hashing and verify. which page/ php script will it be inside?

    ReplyDelete
  54. Keep on getting smtp auht error. :( SMTP Error: Could not authenticate.

    ReplyDelete
  55. Wrong article lol sorry - codingcage.com/2015/09/login-registration-email-verification-forgot-password-php

    ReplyDelete
  56. Hi, Thanks for this tutorial it's just what I was looking for. Most others are really out of date and I find your approach very simple and easy to understand. I especially like how you explain each block of code (great for newbies like me!).

    Just one thing I noticed - when I downloaded your script files - in class.user.php (line 70ish) the function is called `public function doLogout()`. However here on the tutorial page it's called `public function logout()`. This had me puzzled for a while as I was following your tutorial here and had half the code written, I then decided to download the rest of the files, and my files didn't match! My logour wouldn't work and kept throwing an unknown function error.

    No big deal, if anybody else is reading this make sure ALL your functions are named the same or you will have issues like I did

    Thanks again, can't wait for your other tutorials :)

    ReplyDelete
    Replies
    1. Hello Johnny,
      thanks for reminding me to update this post, actually i forgot to update this post after replacing downloading link from box to dropbox, ok i will update this script very soon, and use one files which are in downloadable file. do let me know if your query get solved or not

      Delete
  57. I am getting error when logging in:

    "Fatal error: Call to a member function prepare() on a non-object in class_user.php on line 22"

    {
    private $db;

    function __contruct()
    {
    $this->db = $DB_con;
    }

    public function login($uname, $upass)
    {
    try
    {
    $stmt = $this->db->prepare("SELECT name FROM user WHERE name=:uname AND password=:upass");

    ReplyDelete
    Replies
    1. Hi prius,
      it seems you have make some changes in this script, otherwise it's working, ok it can be modified but make sure you have properly declared the bindparams with uname and upass ?

      Delete
    2. use query() instead of prepare() in User.php

      Delete
    3. My code displays an unknown variable $db
      class user{
      private $db;
      function __construct($DB_conn){
      }
      Any help would be greatly appreciated

      Delete
  58. Hi, thx for this awesome tutorial. can i ask request for another download link because i cant view the download page not sure why or maybe u can just post the logout.php only.. tq

    ReplyDelete
    Replies
    1. download link is working, and all the files are there in the downloadable folder ...

      Delete
  59. Hey there, i didnt alter you script in any way but im still getting an error::

    Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\xampp\htdocs\Login-Signup-PDO-OOP\class.user.php:19 Stack trace: #0 C:\xampp\htdocs\Login-Signup-PDO-OOP\sign-up.php(36): USER->runQuery('SELECT user_nam...') #1 {main} thrown in C:\xampp\htdocs\Login-Signup-PDO-OOP\class.user.php on line 19

    ReplyDelete
  60. When I try to log in with my account(which is registered already), it even displays "Wrong Details" so what you think is my error ? and where did you place the paasswordhash i can't find it in your zip file or I am blind(joke) :D

    ReplyDelete
  61. Can you add something where it will automatically create a database so that manually copy pasting the sql command in the command prompt is not needed

    ReplyDelete
  62. Hello PRADEEP, this code really help me.. can i ask something.. is there any update in role login.. i'm actually in my test page where i can log in admin and normal user.. how to authenticate user?

    ReplyDelete
  63. Hi,I have problems with user class in file dbconfig.php

    Fatal error: Class 'user' not found in C:\xampp\htdocs\CDR\Dbconfig.php on line 22

    ReplyDelete
  64. Fatal error: Class 'user' not found in C:\xampp\htdocs\CDR\Dbconfig.php on line 22

    Can you help me ??

    ReplyDelete
    Replies
    1. have u configured your database correctly?

      Delete
  65. I used this script and i work well, untill i sign up and i logged in i was corrected to the home page. i wanted to logout but it didnt work, im stuck on the home sreen. I dont know if anyone still answers these questions but u will never find out if you now try right?

    I hope someone can help me with this. I changed some bits and pieces of the code to make it look like i did not copy it from the internet, but i doubt it that that is the problem.

    Rainier,

    ReplyDelete
  66. This looks great! It worked fine for me, but I have a concern: It seems there are additional measures you could/should take to prevent hacking, such as via SQL injection. I see you're using DBO::prepare, which helps to prevent SQL injection, according to some references [1][2] this may not be enough. In [2], author recommends also setting the following attribute:
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    In your code, you use:
    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    What measures are you taking (besides DBO::prepare) to prevent hacking?

    [1] http://php.net/manual/en/pdo.prepare.php
    [2] http://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection

    ReplyDelete
  67. This looks great! It worked fine for me, but I have a concern: It seems there are additional measures you could/should take to prevent hacking, such as via SQL injection. I see you're using DBO::prepare, which helps to prevent SQL injection, according to some references [1][2] this may not be enough. In [2], author recommends also setting the following attribute:
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    In your code, you use:
    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    What measures are you taking (besides DBO::prepare) to prevent hacking?

    [1] http://php.net/manual/en/pdo.prepare.php
    [2] http://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection

    ReplyDelete
  68. in home.php you have
    $stmt = $auth_user->runQuery("SELECT * FROM users WHERE user_id=:user_id");

    can you please explain the significance of the colon (:) in the select statement, WHERE user_id = :user_id

    ReplyDelete
  69. Hello Pradeep, thank you so much for all your wonderful tutorials. They are incredibly helpful with my projects :)

    Could you possibly explain to me how a registered user could update their profile?
    Or is there already a tutorial explaining this?

    Thank you so much in advance.
    With kind regards,
    Lloyd

    ReplyDelete
  70. Hi I have this problem help

    SMTP Error: Could not connect to SMTP host.

    ReplyDelete
  71. hello pradeep,
    tutorial was awesome and easily explained by you, thanks to you and your all tutorials, i have learn lot's of from this website... Visit hire php developer

    Regards Sanjay

    ReplyDelete
  72. Muchas gracias, tuve problemas al inicio ya que ingrese usuario contraseña, correo de forma manual en la base de datos... claro al validar los datos me marcaba error. Después entendí como es el proceso, una vez más gracias.

    ReplyDelete
  73. muchas gracias por el script.

    ReplyDelete
  74. please make a logout page for this too.m not getting it without that

    ReplyDelete
  75. Hi Thank you for this script. It really helps a lot. But for a newbie like me with no programming background, it will be a big help if you can add a script to recover lost password. I try to read the other tutorial but I can't seem to make the fpass.php there work here.

    ReplyDelete
  76. Hi. what i can, set session timeout? after 30 seconds, automatic logout, please, helpme

    ReplyDelete
  77. super tutorial !!! i will use it soon

    ReplyDelete
  78. how to if me want to change or update password ? can u help me ?

    ReplyDelete
  79. The file sign-up.php on this page is different to the file I receive when I click on download script. Which is the correct one?

    ReplyDelete
  80. hey bud, nice script.
    How about adding feature, to login with facebook and if there is no account associated then send user to registration page?

    ReplyDelete
  81. Awesome, PRADEEP..

    Worked greatly on localhost, but when put online hosting, while signing in, it gives the following error:

    500 - Internal server error.
    There is a problem with the resource you are looking for, and it cannot be displayed.

    Is it related to security?

    Thank you

    ReplyDelete
  82. Hello Pradeep, great tutorial. I was wondering if there was another tutorial that uses this script to do email verification and password reset? I am currently trying to blend your other tutorial that does email verification and password reset together with this script... but having troubles. THanks

    ReplyDelete
  83. Its Rashid Here
    Welldone, very informative and great work.
    Stay blessed dear

    ReplyDelete
  84. Hi, thanks for the amazing tutorial. Could you please help me to set up a redirection for admin dashboard? I'm trying to have user dashboard separately from admin dashboard. Many thanks for your help ;)

    ReplyDelete
  85. Hi, many thanks for this tutorial, could you help me tu create a new class for admin? i'm trying to create a dashboard for admin which should be different from user dashboard. Many thanks :)

    ReplyDelete
  86. hi, first that all congratulation, to you, the code session php is amazing.

    now

    i have some problem,
    I click in, lost the password, after check my email,
    so, when i click the link, google show me the error in the proxy
    this is what they show me

    can you help me please.. how can i fix it

    http://localhost/x/resetpass.php?id=Mg==&code=37c76fd072ab928ae43120b3f3e3bd6a

    ReplyDelete
  87. hi, first that all congratulation, to you, the code session php is amazing.

    now

    i have some problem,
    I click in, lost the password, after check my email,
    so, when i click the link, google show me the error in the proxy
    this is what they show me

    can you help me please.. how i can fix it

    http://localhost/x/resetpass.php?id=Mg==&code=37c76fd072ab928ae43120b3f3e3bd6a

    ReplyDelete
  88. I am new to php, but 70% i am able to understands about this login concepts which helps to improve my programming skills .thanks a lot your way of presentation.


    Php Training in Chennai







    ReplyDelete
  89. Greetings,

    I have a problem with sessions. After successfully logged in and i went back to home page.
    I noticed, in the navigation menu, it isn't changed. There is no 'view profile' button on it.

    What can be wrong here?

    ReplyDelete
  90. logout is not working! even if i click logout again it goes to home page

    ReplyDelete
  91. Your tutorial has been extremely useful for me. I can't thank you enough so letting you know my appreciation through this comment was the least I could do. Thanks again

    ReplyDelete
  92. God keep blessing you for your great efforts!!! and please keep you alive and fully healthy so we can keep learning great stuff for you. IJN Amen!

    ReplyDelete
  93. So many questions and request!!! same here, BUT i want to say BIG THANK YOU to you bro, May God keep blessing you and keep you in good health so that we get more quality stuff from you. THANK YOU BRO

    ReplyDelete
  94. I am a beginner to sql and php and want to implement this on a new site I have. I see in the dbconfig.php it has these statements, but you are saying I must add this additional code to the dbconfig.php ? I don't get it. Can't I just upload the raw dbconfig.php file the way it is?

    class Database
    {
    private $host = "localhost";
    private $db_name = "dblogin";
    private $username = "root";
    private $password = "";
    public $conn;

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

    setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    }


    include_once 'class.user.php';
    $user = new USER($DB_con);



    ReplyDelete
  95. for security purpose, you have to add:
    $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    in your connection

    ReplyDelete
  96. Thank very much!
    Install and everything works like a charm. Never happened before (with other´s scripts)

    ReplyDelete
  97. guys i need help i am confused. in the website login veryfication does not work you can see problem www.wanjia.gq
    when i create user and want to login with it, shows error wrong details

    ReplyDelete
  98. Great Coding!!! Best I have seen. I have one small error.

    Connection error: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: NO)


    What am I missing on my signup page?

    Thank you
    Timothy

    ReplyDelete
    Replies
    1. I think you haven't logged in with the correct details

      Delete
  99. Hi, Just following the tutorial and got a question, where do i add the password hashing into?
    Thanks

    ReplyDelete
  100. @timothy in your script you need to specify a valid username to the MySQL server; it is best to create a user with limited privileges (instead of using the root user)
    .

    ReplyDelete