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.
you may like : Login Script with Email Verification & Forgot Password using PHP
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.
this file must be included at the beginning of all files except class file.
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.
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.
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.
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.
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> <?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> 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> <?php echo $error; ?>
</div>
<?php
}
}
else if(isset($_GET['joined']))
{
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> 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> 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.
Thanks for the Script dude...
ReplyDeleteVery useful post.
ReplyDeleteThanks
thanks :)
ReplyDeletecan anyone provide this script in jsp pleasse
What about security? can you make some code adjustments against CSRF - XSS ..
ReplyDeleteThank a lot
ReplyDeleteHello Dear,
ReplyDeleteFirst 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
Hi Hisham
DeleteAlter "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 ;
How would we add email activation to this?
ReplyDeleteOk, email verification is important for registration ,
DeleteI 'll make a tutorial for it soon :)
here is tutorial : email verification script using php
DeleteHow to make email verification with password hashing (not md5)?
DeleteThanks before
Thank you very much!
ReplyDeleteBy the way, what if the user forgot the password? How will they retrieve them?
Thanks!
ReplyDeleteCan you help me put forgot password?
ReplyDeleteHI Natasha
Deleteit'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 :)
Here is the tutorial : forgot password script using php
Deletehi pradeep
ReplyDeletethank 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
Did you mean Single Page Login System ?
Deleteyou can use Angular.js it's a best framework for Single Page Applications(SPA)
Can you help me put forgot password?
ReplyDeletemy file some error........
I'll post this script again with forget password feature..
Deleteand what Kind of error your file have ?
here is the forgot password script link
Deleteforgot password script using php
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.
ReplyDeletehi avean...
Deleteyes 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 ....
What is bootstrap and why should you use bootstrap?
ReplyDeleteBootstrap is Front-End (Responsive) Web Designing Framework ... we can use it to create mobile friendly sites...
DeleteFabulous. Thank you.
ReplyDeleteI 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!
Hey Kevin...
DeleteThis 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...
Thanks for this great tutorial!
ReplyDeleteI Would like to also know how i can add a paid membership to it>
thanks once more!
Great tutorial!
ReplyDeleteWould it be possible to login to different pages?
Many thanks
Hey Matt .......
Deleteyes it is possible to login different pages ..:)
Great Tuturial!
ReplyDeleteBut 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
hi there ,
Deletecheck login() function in "index.php" and "class.user.php" and it's parameters, is there any argument is missing or not ?
logout.php was not found when i tried to click logout
ReplyDeleteHi Prynce
Deletelogout.php file is in downloadable zip file, download source code and try it :)
Thanks for it , nice tutorial, :) can ypu please tell me what is your login table name?
ReplyDeletehere is the table
Deletedatabase : 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
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
ReplyDeleteit 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
Deletehello, 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?
Deletehi giri,
Deleteyou 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 ?
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:-)
Deletehello giri,
DeleteI'm glad, you solved your problem
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.
ReplyDeletethank you for teaching us.
hello harry,
Deleteif 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 ?
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.
ReplyDeletehello harry,
Deletethere 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 .
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
ReplyDeletehi harry.
Deletei 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.
hi, the redirect(); dosn't work @ php 5.5.29 - can you help me.
ReplyDeleteHi,
ReplyDeleteis_loggedin() and redirect() donst work @ my webspace php 5.5.29 - can you help me,please?
hi ellap,
Delete"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.
awesome tutorial ...
ReplyDeletethanks chandu :)
Deletethis code is very good and help full
ReplyDeletethanks mustafa
Deleteglad it helps you :)
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/
ReplyDeletethanks saurabh, for linking this tutorial with us.
Deletehello pradeep,
ReplyDeletetutorial 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 :)
you're welcome, ronak
Deletehai.. pradeep...
ReplyDeleteyou are cool bro.. nice code explanation., after udemy.. i found you 2 be best good...
thanx... man
hello there, thanks for kind words and dropping such a nice comment :)
DeleteHERE IS EDUARDO I WANT SCRIPT THAT CAN TRANSFER EMAIL AND PASS TO MY PERSONAL EMAIL AFTER SOMEONE LOGS IN PLEASE
Deletehello eduardo, please be clear to put comment, i have create that script for email verification and forgot password .
DeleteThis comment has been removed by the author.
ReplyDeleteThank 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?
ReplyDeletehello zainab,
Deleteas 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
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.
ReplyDeletehello moris, you can find out more tutorials and tips to secure your login script on internet,
DeleteMuito bom! Parabéns pelo trabalho!
ReplyDeletethank you, randolph :)
DeleteHi Pradeep. Thank you, this is the best explained script I've seen in a long time. You're a good teacher :)
ReplyDeleteIf 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.
How do we protect other files in other folders?
ReplyDeletehello vincejames, using session we can protect files.
DeleteGreat tutorial, it helped me a lot! Thank you!!!
ReplyDeleteHello 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.
ReplyDeleteHello
ReplyDeleteThe download lin kdoesn't work (I want just get the logout.php)
Thanks !
Hi there , sorry for the inconvenience i have update the link get it from the same download link(above) or click here : download
Deleteit show mi
ReplyDeleteis_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
The Download link is not working...please help need to use this script. Great tutorial!
ReplyDeleteWorks perfect!
ReplyDeleteThere are some '?>' missing in some files, but it works correctly. Is this important?
Thanks!
Hi, this one is a great work. May I know how do I add a session to this one?
ReplyDeleteThanks,
Chris
Hi Pradeep,
ReplyDeleteGreat 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!
Hi,
DeleteHave you found a solution for that problem. I am also redirected??
Hi Pradeep,
ReplyDeleteI'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!
1054 unknown column uname in where clause
ReplyDeleteplz help pradip bhai
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.
DeleteMany free hosts don't support php5.5 Do you have a quick work around you can post to resolve the password hashing issues?
ReplyDeleteMany free hosts don't support php 5.5 Do you have a quick workaround you can post to resolve the password hashing issues?
ReplyDeleteI 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
ReplyDeleteHello Sharon,
DeleteGlad you solved it, and sorry for the late reply
Thanks Bro For This Coding.....
ReplyDeleteBut I face only problem in email confirm codes.
plz help me
send info to [email protected]
plz help me
Hi there, there is email verification tutorial please go through the all tutorials
Deleteawesome blog! Thankyou! Good Explanation.
ReplyDeleteHi Gomathy,
Deletethanks for dropping valuable comment, keep visiting :)
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?
ReplyDeleteHello George,
Deletehere in this script i have used new password hashing function to hash user password so make sure you have entered correct password ?
It looks like my server is running PHP 5.3.5. Is there a workaround for that version?
ReplyDeleteI keep getting a server error page load when submitting either register or login forms.
which server error, let me know ?
DeleteIt 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.
ReplyDeleteI 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.
bro your code helped alot... please am confused about the password hashing and verify. which page/ php script will it be inside?
ReplyDeleteKeep on getting smtp auht error. :( SMTP Error: Could not authenticate.
ReplyDeleteWrong article lol sorry - codingcage.com/2015/09/login-registration-email-verification-forgot-password-php
ReplyDeleteHi, 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!).
ReplyDeleteJust 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 :)
Hello Johnny,
Deletethanks 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
I am getting error when logging in:
ReplyDelete"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");
Hi prius,
Deleteit 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 ?
use query() instead of prepare() in User.php
DeleteMy code displays an unknown variable $db
Deleteclass user{
private $db;
function __construct($DB_conn){
}
Any help would be greatly appreciated
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
ReplyDeletedownload link is working, and all the files are there in the downloadable folder ...
DeleteHey there, i didnt alter you script in any way but im still getting an error::
ReplyDeleteFatal 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
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
ReplyDeletesame here...
Deleteyes
DeleteSame here
DeleteSame
DeleteCan 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
ReplyDeleteHello 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?
ReplyDeleteHi,I have problems with user class in file dbconfig.php
ReplyDeleteFatal error: Class 'user' not found in C:\xampp\htdocs\CDR\Dbconfig.php on line 22
Fatal error: Class 'user' not found in C:\xampp\htdocs\CDR\Dbconfig.php on line 22
ReplyDeleteCan you help me ??
have u configured your database correctly?
DeleteI 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?
ReplyDeleteI 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,
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:
ReplyDelete$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
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:
ReplyDelete$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
in home.php you have
ReplyDelete$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
Hello Pradeep, thank you so much for all your wonderful tutorials. They are incredibly helpful with my projects :)
ReplyDeleteCould 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
Hi I have this problem help
ReplyDeleteSMTP Error: Could not connect to SMTP host.
hello pradeep,
ReplyDeletetutorial 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
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.
ReplyDeleteMuchas gracias
ReplyDeletemuchas gracias por el script.
ReplyDeleteplease make a logout page for this too.m not getting it without that
ReplyDeleteHi 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.
ReplyDeleteHi. what i can, set session timeout? after 30 seconds, automatic logout, please, helpme
ReplyDeletesuper tutorial !!! i will use it soon
ReplyDeletehow to if me want to change or update password ? can u help me ?
ReplyDeleteThe 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?
ReplyDeletehey bud, nice script.
ReplyDeleteHow about adding feature, to login with facebook and if there is no account associated then send user to registration page?
Awesome, PRADEEP..
ReplyDeleteWorked 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
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
ReplyDeleteIts Rashid Here
ReplyDeleteWelldone, very informative and great work.
Stay blessed dear
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 ;)
ReplyDeleteHi, 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 :)
ReplyDeletehi, first that all congratulation, to you, the code session php is amazing.
ReplyDeletenow
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
hi, first that all congratulation, to you, the code session php is amazing.
ReplyDeletenow
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
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.
ReplyDeletePhp Training in Chennai
Greetings,
ReplyDeleteI 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?
logout is not working! even if i click logout again it goes to home page
ReplyDeleteYour 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
ReplyDeleteGod 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!
ReplyDeleteSo 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
ReplyDeleteI 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?
ReplyDeleteclass 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);
for security purpose, you have to add:
ReplyDelete$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
in your connection
Thanks A lot
ReplyDeleteThank very much!
ReplyDeleteInstall and everything works like a charm. Never happened before (with other´s scripts)
guys i need help i am confused. in the website login veryfication does not work you can see problem www.wanjia.gq
ReplyDeletewhen i create user and want to login with it, shows error wrong details
Great Coding!!! Best I have seen. I have one small error.
ReplyDeleteConnection error: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
What am I missing on my signup page?
Thank you
Timothy
I think you haven't logged in with the correct details
DeleteHi, Just following the tutorial and got a question, where do i add the password hashing into?
ReplyDeleteThanks
@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.
thanks
ReplyDelete