Hi coders, In this tutorial post we have a simple login and registration script with email verification along with forgot password recovery feature using PHP and MySQL, Well advanced PHP Programming must follow proper Object Oriented(OOP) approach so i have used here OOP with PDO(PHP Data Object), and PDO is recommended to use since mysql extension is deprecated, ok let's come to the post. Well to avoid fake registrations we need to verify a newly registered user with their email id, So to send verification email i have used here PHPMailer library which is awesome mailer library, i have already posted a tutorial about sending plain & HTML format emails using PHPMailer you can check them out. so set your domain smtp credentials, if you don't have domain smtp you can also use your Gmail credentials as well using gmail smtp(smtp.gmail.com) so lets have a look at this tutorial and see php code to send email while registration you can also try this in your localhost also. let's code.
Note I have used here Bootstrap to make better user Interface of this script so scripts looks little lengthy.
read also : jQuery Ajax Registration Form with PHP MySQL
after database creation we have to create following files which are :
- runQuery() : executes a Query.
- lastID() : return a last insert id.
- register() : register new user.
- login() : to login user.
- is_logged_in() : return users session is active or not.
- logout() : to destroy users session.
- send_mail() : to send mail at user registration and send forgot password reset link.
i have used here PHPMailer to send emails using gmail smtp so you can use in your localhost server.
NOTE : I have Skip validation part over here and used only HTML5 validation attributes and used MD5() Password Encryption Function, if you use PHP5.5 then you must use New Password Hashing Functions Here.
after registration a user will get mailed to his mail account to activate and verify his/her account and redirects to the "verify.php" file.
send_mail() function send a confirmation link to the user registered email.
That's it
we have created here login & registration script with email verification along with forgot password recovery feature, we already have a login and registrations tutorials but i have to decide to post email verification and forgot password tutorial after getting email requests from my readers so enjoy...
read also : jQuery Ajax Registration Form with PHP MySQL
Database and Table
import and run this sql code to create database and table
CREATE TABLE IF NOT EXISTS `tbl_users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(100) NOT NULL,
`userEmail` varchar(100) NOT NULL UNIQUE,
`userPass` varchar(100) NOT NULL,
`userStatus` enum('Y','N') NOT NULL DEFAULT 'N',
`tokenCode` varchar(100) NOT NULL,
PRIMARY KEY (`userID`)
)
after database creation we have to create following files which are :
- dbconfig.php
- class.user.php
- index.php
- signup.php
- verify.php
- home.php
- fpass.php
- resetpass.php
- logout.php
dbconfig.php
In this file we have a simple database connection code using Database class, and one dbConnection function which connects database<?php
class Database
{
private $host = "localhost";
private $db_name = "dbtest";
private $username = "root";
private $password = "";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
class.user.php
include "dbconfig.php" file at the beginning of this class file to make use of database and within "__construct()" function create new object of "Database()" class as "$db" as shown in this file- runQuery() : executes a Query.
- lastID() : return a last insert id.
- register() : register new user.
- login() : to login user.
- is_logged_in() : return users session is active or not.
- logout() : to destroy users session.
- send_mail() : to send mail at user registration and send forgot password reset link.
i have used here PHPMailer to send emails using gmail smtp so you can use in your localhost server.
<?php
require_once 'dbconfig.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function lasdID()
{
$stmt = $this->conn->lastInsertId();
return $stmt;
}
public function register($uname,$email,$upass,$code)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO tbl_users(userName,userEmail,userPass,tokenCode)
VALUES(:user_name, :user_mail, :user_pass, :active_code)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function login($email,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_users WHERE userEmail=:email_id");
$stmt->execute(array(":email_id"=>$email));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['userPass']==md5($upass))
{
$_SESSION['userSession'] = $userRow['userID'];
return true;
}
else
{
header("Location: index.php?error");
exit;
}
}
else
{
header("Location: index.php?inactive");
exit;
}
}
else
{
header("Location: index.php?error");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
$_SESSION['userSession'] = false;
}
function send_mail($email,$message,$subject)
{
require_once('mailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->AddAddress($email);
$mail->Username="[email protected]";
$mail->Password="yourgmailpassword";
$mail->SetFrom('[email protected]','Coding Cage');
$mail->AddReplyTo("[email protected]","Coding Cage");
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->Send();
}
}
signup.php | Email Verification
create "signup.php" file and paste following code inside file and include "class.user.php" file at the beginning of this file and create new object to access class files function as shown in the file.NOTE : I have Skip validation part over here and used only HTML5 validation attributes and used MD5() Password Encryption Function, if you use PHP5.5 then you must use New Password Hashing Functions Here.
after registration a user will get mailed to his mail account to activate and verify his/her account and redirects to the "verify.php" file.
send_mail() function send a confirmation link to the user registered email.
<?php
session_start();
require_once 'class.user.php';
$reg_user = new USER();
if($reg_user->is_logged_in()!="")
{
$reg_user->redirect('home.php');
}
if(isset($_POST['btn-signup']))
{
$uname = trim($_POST['txtuname']);
$email = trim($_POST['txtemail']);
$upass = trim($_POST['txtpass']);
$code = md5(uniqid(rand()));
$stmt = $reg_user->runQuery("SELECT * FROM tbl_users WHERE userEmail=:email_id");
$stmt->execute(array(":email_id"=>$email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry !</strong> email allready exists , Please Try another one
</div>
";
}
else
{
if($reg_user->register($uname,$email,$upass,$code))
{
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = "
Hello $uname,
<br /><br />
Welcome to Coding Cage!<br/>
To complete your registration please , just click following link<br/>
<br /><br />
<a href='http://www.SITE_URL.com/verify.php?id=$id&code=$code'>Click HERE to Activate :)</a>
<br /><br />
Thanks,";
$subject = "Confirm Registration";
$reg_user->send_mail($email,$message,$subject);
$msg = "
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Success!</strong> We've sent an email to $email.
Please click on the confirmation link in the email to create your account.
</div>
";
}
else
{
echo "sorry , Query could no execute...";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Signup | Coding Cage</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body id="login">
<div class="container">
<?php if(isset($msg)) echo $msg; ?>
<form class="form-signin" method="post">
<h2 class="form-signin-heading">Sign Up</h2><hr />
<input type="text" class="input-block-level" placeholder="Username" name="txtuname" required />
<input type="email" class="input-block-level" placeholder="Email address" name="txtemail" required />
<input type="password" class="input-block-level" placeholder="Password" name="txtpass" required />
<hr />
<button class="btn btn-large btn-primary" type="submit" name="btn-signup">Sign Up</button>
<a href="index.php" style="float:right;" class="btn btn-large">Sign In</a>
</form>
</div> <!-- /container -->
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
verify.php
create new file as "verify.php" and paste following code inside this file, after redirecting from email this file will generate a QueryString as "id=something&code=something" and based on activation code the userStatus will update from "N" to "Y" means "inactive" to "active"
<?php
require_once 'class.user.php';
$user = new USER();
if(empty($_GET['id']) && empty($_GET['code']))
{
$user->redirect('index.php');
}
if(isset($_GET['id']) && isset($_GET['code']))
{
$id = base64_decode($_GET['id']);
$code = $_GET['code'];
$statusY = "Y";
$statusN = "N";
$stmt = $user->runQuery("SELECT userID,userStatus FROM tbl_users WHERE userID=:uID AND tokenCode=:code LIMIT 1");
$stmt->execute(array(":uID"=>$id,":code"=>$code));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if($row['userStatus']==$statusN)
{
$stmt = $user->runQuery("UPDATE tbl_users SET userStatus=:status WHERE userID=:uID");
$stmt->bindparam(":status",$statusY);
$stmt->bindparam(":uID",$id);
$stmt->execute();
$msg = "
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>WoW !</strong> Your Account is Now Activated : <a href='index.php'>Login here</a>
</div>
";
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> Your Account is allready Activated : <a href='index.php'>Login here</a>
</div>
";
}
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> No Account Found : <a href='signup.php'>Signup here</a>
</div>
";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Confirm Registration</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body id="login">
<div class="container">
<?php if(isset($msg)) { echo $msg; } ?>
</div> <!-- /container -->
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
index.php / Login Page
index.php as login page which will take email id and password to access users home page if the details are wrong it will show appropriate message, with forgot password link. only email verified user can log in and access member page.
<?php
session_start();
require_once 'class.user.php';
$user_login = new USER();
if($user_login->is_logged_in()!="")
{
$user_login->redirect('home.php');
}
if(isset($_POST['btn-login']))
{
$email = trim($_POST['txtemail']);
$upass = trim($_POST['txtupass']);
if($user_login->login($email,$upass))
{
$user_login->redirect('home.php');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login | Coding Cage</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body id="login">
<div class="container">
<?php
if(isset($_GET['inactive']))
{
?>
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry!</strong> This Account is not Activated Go to your Inbox and Activate it.
</div>
<?php
}
?>
<form class="form-signin" method="post">
<?php
if(isset($_GET['error']))
{
?>
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Wrong Details!</strong>
</div>
<?php
}
?>
<h2 class="form-signin-heading">Sign In.</h2><hr />
<input type="email" class="input-block-level" placeholder="Email address" name="txtemail" required />
<input type="password" class="input-block-level" placeholder="Password" name="txtupass" required />
<hr />
<button class="btn btn-large btn-primary" type="submit" name="btn-login">Sign in</button>
<a href="signup.php" style="float:right;" class="btn btn-large">Sign Up</a><hr />
<a href="fpass.php">Lost your Password ? </a>
</form>
</div> <!-- /container -->
<script src="bootstrap/js/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
Home.php / Member Page
after verifying and email confirmation finally user will become verified user of site and can access this member page. this page is for registered members.
<?php
session_start();
require_once 'class.user.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<title><?php echo $row['userEmail']; ?></title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">Member Home</a>
<div class="nav-collapse collapse">
<ul class="nav pull-right">
<li class="dropdown">
<a href="#" role="button" class="dropdown-toggle" data-toggle="dropdown"> <i class="icon-user"></i>
<?php echo $row['userEmail']; ?> <i class="caret"></i>
</a>
<ul class="dropdown-menu">
<li>
<a tabindex="-1" href="logout.php">Logout</a>
</li>
</ul>
</li>
</ul>
<ul class="nav">
<li class="active">
<a href="https://codingcage.com/">Coding Cage</a>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">Tutorials <b class="caret"></b>
</a>
<ul class="dropdown-menu" id="menu1">
<li><a href="https://codingcage.com/search/label/PHP OOP">PHP OOP</a></li>
<li><a href="https://codingcage.com/search/label/PDO">PHP PDO</a></li>
<li><a href="https://codingcage.com/search/label/jQuery">jQuery</a></li>
<li><a href="https://codingcage.com/search/label/Bootstrap">Bootstrap</a></li>
<li><a href="https://codingcage.com/search/label/CRUD">CRUD</a></li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
<!--/.fluid-container-->
<script src="bootstrap/js/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="assets/scripts.js"></script>
</body>
</html>
logout.php
simple script and code to logout current logged in user and redirects user to "index.php" login page.
<?php
session_start();
require_once 'class.user.php';
$user = new USER();
if(!$user->is_logged_in())
{
$user->redirect('index.php');
}
if($user->is_logged_in()!="")
{
$user->logout();
$user->redirect('index.php');
}
?>
fpass.php | Forgot Password
if user forgets password then this page will ask verified users email and send password reset link to his email account to reset his password and redirects to "resetpass.php" with QueryString id="something&code=something", this will update tokenCode field in database table and in "resetpass.php" it will match the code then user finally can reset password.
<?php
session_start();
require_once 'class.user.php';
$user = new USER();
if($user->is_logged_in()!="")
{
$user->redirect('home.php');
}
if(isset($_POST['btn-submit']))
{
$email = $_POST['txtemail'];
$stmt = $user->runQuery("SELECT userID FROM tbl_users WHERE userEmail=:email LIMIT 1");
$stmt->execute(array(":email"=>$email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
$id = base64_encode($row['userID']);
$code = md5(uniqid(rand()));
$stmt = $user->runQuery("UPDATE tbl_users SET tokenCode=:token WHERE userEmail=:email");
$stmt->execute(array(":token"=>$code,"email"=>$email));
$message= "
Hello , $email
<br /><br />
We got requested to reset your password, if you do this then just click the following link to reset your password, if not just ignore this email,
<br /><br />
Click Following Link To Reset Your Password
<br /><br />
<a href='http://www.SITEURL.com/resetpass.php?id=$id&code=$code'>click here to reset your password</a>
<br /><br />
thank you :)
";
$subject = "Password Reset";
$user->send_mail($email,$message,$subject);
$msg = "<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
We've sent an email to $email.
Please click on the password reset link in the email to generate new password.
</div>";
}
else
{
$msg = "<div class='alert alert-danger'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry!</strong> this email not found.
</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Forgot Password</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body id="login">
<div class="container">
<form class="form-signin" method="post">
<h2 class="form-signin-heading">Forgot Password</h2><hr />
<?php
if(isset($msg))
{
echo $msg;
}
else
{
?>
<div class='alert alert-info'>
Please enter your email address. You will receive a link to create a new password via email.!
</div>
<?php
}
?>
<input type="email" class="input-block-level" placeholder="Email address" name="txtemail" required />
<hr />
<button class="btn btn-danger btn-primary" type="submit" name="btn-submit">Generate new Password</button>
</form>
</div> <!-- /container -->
<script src="bootstrap/js/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
resetpass.php
this page will be redirected from user email account to reset password, as in the QueryString there is id and code and based on code a user can reset his forgotten password, if a QueryString is set then this page can be opened. after resetting password user will be redirected to the login page.
<?php
require_once 'class.user.php';
$user = new USER();
if(empty($_GET['id']) && empty($_GET['code']))
{
$user->redirect('index.php');
}
if(isset($_GET['id']) && isset($_GET['code']))
{
$id = base64_decode($_GET['id']);
$code = $_GET['code'];
$stmt = $user->runQuery("SELECT * FROM tbl_users WHERE userID=:uid AND tokenCode=:token");
$stmt->execute(array(":uid"=>$id,":token"=>$code));
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(isset($_POST['btn-reset-pass']))
{
$pass = $_POST['pass'];
$cpass = $_POST['confirm-pass'];
if($cpass!==$pass)
{
$msg = "<div class='alert alert-block'>
<button class='close' data-dismiss='alert'>×</button>
<strong>Sorry!</strong> Password Doesn't match.
</div>";
}
else
{
$stmt = $user->runQuery("UPDATE tbl_users SET userPass=:upass WHERE userID=:uid");
$stmt->execute(array(":upass"=>$cpass,":uid"=>$rows['userID']));
$msg = "<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
Password Changed.
</div>";
header("refresh:5;index.php");
}
}
}
else
{
exit;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Password Reset</title>
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<link href="assets/styles.css" rel="stylesheet" media="screen">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body id="login">
<div class="container">
<div class='alert alert-success'>
<strong>Hello !</strong> <?php echo $rows['userName'] ?> you are here to reset your forgetton password.
</div>
<form class="form-signin" method="post">
<h3 class="form-signin-heading">Password Reset.</h3><hr />
<?php
if(isset($msg))
{
echo $msg;
}
?>
<input type="password" class="input-block-level" placeholder="New Password" name="pass" required />
<input type="password" class="input-block-level" placeholder="Confirm New Password" name="confirm-pass" required />
<hr />
<button class="btn btn-large btn-primary" type="submit" name="btn-reset-pass">Reset Your Password</button>
</form>
</div> <!-- /container -->
<script src="bootstrap/js/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
That's it
we have created here login & registration script with email verification along with forgot password recovery feature, we already have a login and registrations tutorials but i have to decide to post email verification and forgot password tutorial after getting email requests from my readers so enjoy...
I tried the script and the function Enter e-mail does not work very CAN SEE come and set it come fix it ?
ReplyDeleteit's working,
Delete"function send_mail($email,$message,$subject)"
set your gmail id and password in this function and try it in your localhost
hello Pradeep
ReplyDeletethank you very much for this tutorial, I learned a lot with with it
usually we have to separate users according their roles (permissions)
with 2 roles : 'admin' and 'user', each one must be redirected to his page
'admin' redirected to 'admin.php' and 'user' redirected to 'user.php'
so I added in the database a field named 'role' which contains admin or user
--------------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS `tbl_users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(100) NOT NULL,
`userEmail` varchar(100) NOT NULL,
`userPass` varchar(100) NOT NULL,
`userRole` varchar(100) NOT NULL,
`userStatus` enum('Y','N') NOT NULL DEFAULT 'N',
`tokenCode` varchar(100) NOT NULL,
PRIMARY KEY (`userID`),
UNIQUE KEY `userEmail` (`userEmail`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--------------------------------------------------------------------------------------------------------
I am a novice in php, please confirm me if the following addings are ok :
-1. class.user.php
--------------------------
if($userRow['userPass']==md5($upass))
{
$_SESSION['userSession'] = $userRow['userID'];
$_SESSION['userRole'] = $userRow['userRole'];
return true;
}
-2. signup.php
---------------------
if($reg_user->is_logged_in()!="" AND $_SESSION['userRole'] = ('admin'))
{
$reg_user->redirect('admin.php');
} elseif ($reg_user->is_logged_in()!="" AND $_SESSION['userRole'] = ('user')) {
$reg_user->redirect('user.php');
}
-3. fpass.php
-------------------
if($user->is_logged_in()!="" AND $_SESSION['userRole'] = ('admin'))
{
$user->redirect('admin.php');
} elseif ($user->is_logged_in()!="" AND $_SESSION['userRole'] = ('user')) {
$user->redirect('user.php');
}
-4. index.php
-------------------
if($user_login->is_logged_in()!="" AND $_SESSION['userRole'] = ('admin'))
{
$user_login->redirect('admin.php');
} elseif ($user_login->is_logged_in()!="" AND $_SESSION['userRole'] = ('user')) {
$user_login->redirect('user.php');
}
if(isset($_POST['btn-login']))
{
$email = trim($_POST['txtemail']);
$upass = trim($_POST['txtupass']);
if($user_login->login($email,$upass) AND $_SESSION['userRole'] = ('admin'))
{
$user_login->redirect('admin.php');
} elseif ($user_login->login($email,$upass) AND $_SESSION['userRole'] = ('user')) {
$user_login->redirect('user.php');
}
}
?>
thank you Pradeep
hi hafid,
Deletei will post a tutorial about role based login system , soon : )
you are the best teacher in the wwhole internet!
Deletehello there.
Deletethanks for kind words.. and keep visiting :)
Any Updates on the role?
DeleteHello,
ReplyDeleteWell I got this error:
SMTP Error: Could not authenticate.
Any fix??
P.S: I didn't change anything in the php.ini and sendmail.ini files, they are as if newly installed.
Hi there,
Deleteplease check your gmail credentials, username, password, port no, and there is no need to do any changes in php.ini file
even i'm getting the same error please rectify or help us what to do..!
DeleteGetting the same error do you how do you solve it?
DeleteThis is what I did to fix that “SMTP Error: Could not authenticate” problem.
DeleteAssuming that your class.user.php section is correct as follow:
require_once('PHPMailer_5.2.4/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->AddAddress($email);
$mail->Username="[email protected]";
$mail->Password="your password";
$mail->SetFrom(' [email protected]',your name);
$mail->AddReplyTo("[email protected]","your name");
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->Send();
If this is what it looks like, besides your email and password, then your settings are correct.
The problem lies with GMAIL. You have to change the security settings to low.
Once you do that, then you are able to send mail.
Hope this helps.
Daniel
You should use password_hash() and password_verify() rather than MD5.
ReplyDeletei have focused on email verification and forgot password in this script, i already wrote a tutorial about login registration with new password hashing functions click here to see
Deletelooking for the same tutorial ...
ReplyDeletethanks pradeep for your all tutorials...
You're Welcome John ..
Deletekeep visiting.... :)
I ADDED SOME FORM ITEMS SUCH AS FIRST NAME, LAST NAME, DEPARTMENT, COURSE CODE, SCHOLARSHIP STATUS. WHEN I TRIED TO SIGN UP IT GIVES ME THE RESULT (SQLSTATE[HY093]: Invalid parameter number: parameter was not definedsorry , Query could no execute... ) PLEASE HELP ME OUT..
ReplyDeleteHi there,
Deletecheck your bindparam() parameters with prepared() statements parameters which you have added
there's must be mismatch you have in the modified script. in register() function
please i need a css code for the registration, login and verification
ReplyDeletethis script is created with bootstrap, and i have created login, registration with this, so you no need to add some custom css, or if you want to add some custom css you can add, bu there's bootstrap is there.
Deletehello! in the home page its only displaying the email address of the user...please how can i display all the input in the database to appear at the home page.. also how do i add a picture from the database to the home page....i dont know php at all... this is what have done at the home page... but its not displaying anything...could you please help me to arrange the home page so it could contain all these inputs that are in these codes and also have a place for passport. i have created the registration page which contains all these inputs and have stored them in my database...pls send the code to my email favor1[email protected]. i will be very graetful. thanks God bless you...
ReplyDeletethis is what i added to the registration form but is not showing in the homepage....
reg ID, first name, last name, date of birth, passport,department,course code,programme,scholarship score, scholarship status.
hello chika,
Deletethis script was just for tutorial purpose only, i written and post this tutorial to explain newbies that how to do email verification and forgot password feature in login system, that's why i showed only user email on the home page, but if you want to show all the fields from the database do the same as i displayed email in home pages title, same you can display like this on home page
<?php
echo $row['userEmail'];
echo $row['first_name'];
echo $row['date_of_birth'];
?>
alter users table and add new fields you want then display them on home page :)
hi thank you so much this tutorial. but i get this error message after registration
ReplyDeleteSMTP Error: Could not connect to SMTP host.
please help
hi there, maybe your credentials are wrong, check the port no, host, username and password.
Deletewhere to check it please i wanna know about it please
Deletehey where to check it please help me :(
Deletehello nimesh ,
Deletecheck these credentials in "class.user.php" there is last function "send_mail()" within this function give your gmail id and password
On the home page where do I find out how to remove "root" and the password so the box is empty
ReplyDeletehello there, you can remove "root" and password in "dbconfig.php" ..
DeleteHello there,
ReplyDeleteI'm royally stuck. Every script works except for one small (well big actually) problem. When I click on the forgot password link in the email it open up a new tab...tries to load the page but the connection times out. Is it a script problem or a setup problem?
I have no idea where to start troubleshooting as the error is a general error that can occur for any site. My code is not throwing any errors at all (I've been debugging it for the last day, probably why) Any ideas?
hello laura, the script is working i have tested it, maybe you have slow net connection problem because it takes while to send mail from localhost or online server as well...
DeleteI feel like I should respond as I felt so stupid once I'd resolved it! The problem resided in the link I was sending via email...as I'm testing locally I put in the IP address...not realising my IP address had changed since I'd written it! So I just wanted to say thanks for the fully working tutorial, now to rub my hands in some form validation ;)
DeleteHi Laura,
Deletethanks for coming back and posting nice comment :)
https://codingcage.com/search/label/Validations
could not authenticate problem is occurring again and again pls reply asap
ReplyDeleteplease check your email, password, or port no
Deletewhat port no. should i try, as u hav mentioned 465 but my smtp port is 25 and normal host port is 80
Deleteits not working on 465 and 587 port
Deleteits done but bro can you put the tutorial for rest pass page because after clicking on the password reste page its doesnt open anything
Deletehello ishank, forgot password feature i working, please check anything unexpected changes made by you, i have posted here complete tutorial.
DeleteHey Pradeep I've been looking through the CSS and there's a lot of it actually too much to read. What I need to know is where do I go to change the colors, and the backgrounds of the pages to match the pages I have already in place?
ReplyDeletehello there, in the beginning of this tutorial i put the note that i have used here bootstrap for designing purpose, so script looks little lengthy
DeleteSorry Pradeep I found what I am looking for you don't have to post a response.
ReplyDeletecan u give the tutorial for making forum in php or to integrate mybb with your website
ReplyDeletePradeep I'm getting this error. Fatal error: require_once(): Failed opening required 'class.smtp.php' (include_path='.:/usr/lib/php5.4') in /homepages/38/d594866348/htdocs/class.phpmailer.php on line 702
ReplyDeleteWhat I don't understand is where is the file "class.smtp.php"? How is this error being generated?
please check your file path ?
DeleteThanks Pradeep i have all good just
ReplyDeleteWe've sent an email to [email protected]. Please click on the password reset link in the email to generate new password.
But
SMTP Error: Could not connect to SMTP host.
por i have 456
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
hi there, maybe your credentials are wrong, host, username and password. if it is work on email verification then it must be work for forgot password.
Deleteive set up my gmail credentials but i still get the "SMTP Error: Could not authenticate." error :( please help
ReplyDeleteI've setup my gmail credentials but i still get the "SMTP Error: Could not authenticate." error :/ Please help, I'm a PHP noob. :(
ReplyDeleteoh cool, it can send e-mails now but when i follow the link to verify i get this error "404 - File or directory not found.
ReplyDeleteThe resource you are looking for might have been removed, had its name changed, or is temporarily unavailable." :/
I'm having this same notification error 404 - File or directory not found after clicking on the link in the email. (The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable) I don't see how Sarah fixed this issue. any help would be appreciated here
Deletehello scott, please give your site name in home.php
Deletehttp://www.SITE_URL.com/verify.php?id=$id&code=$code
replace SITE_URL with your site
when I click 'click here to reset your password', it directs me to this url http://localhost/x/resetpass.php?id=Mg==&code=c5d3943fe877efa260087042cb29cd7f
DeleteYour help is highly appreciated. Thanks so much.
My application get connected on localhost but, when i switch to my server it shows following error message:
ReplyDelete"SMTP Error: Could not connect to SMTP host."
Where could be the issue and solution... thanks in advance
Hello Arastu, it works for both local server and online server, if your application connects on localhost and not on online then please check SMTP credentials , username, password
DeleteOh i got it all to work now, thank you so much for this tutorial, Pradeep :D Keep up the great work!
ReplyDeleteyou're welcome sarah
DeleteGlad it helps you .. :)
It has helped me tons! One more thing though, uhm.. so I tried merging the verification and password reset page because I want the users to change their password first before their account gets activated.. I think there's something wrong with my query? Because when I go to change my password or even type unidentical passwords, it just redirects to the index page when I hit the submit button :T I've checked it a hundred times but I still can't figure out what's wrong *cries*
Deletehere's my code for the activation page:
redirect('index.php');
}
if(isset($_GET['id']) && isset($_GET['code']))
{
$id = base64_decode($_GET['id']);
$code = $_GET['code'];
$statusY = "Y";
$statusN = "N";
$stmt = $user->runQuery("SELECT * FROM tbl_user WHERE user_key=:uid AND user_code=:token LIMIT 1");
$stmt->execute(array(":uid"=>$id,":token"=>$code));
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($rows['user_active']==$statusN)
{
if(isset($_POST['submit']))
{
$pass = $_POST['pass'];
$cpass = $_POST['conpass'];
if($cpass!==$pass)
{
$msg = //passwords dont match
}
else
{
$stmt = $user->runQuery("UPDATE tbl_user SET user_active=:status WHERE user_key=:uID");
$stmt->bindparam(":status",$statusY);
$stmt->bindparam(":uID",$id);
$stmt->execute();
$password = password_hash($cpass, PASSWORD_DEFAULT);
$stmt = $user->runQuery("UPDATE tbl_user SET user_pw=:upass WHERE user_key=:uid");
$stmt->execute(array(":upass"=>$password,":uid"=>$rows['user_key']));
$msg = //password changed and account activated
header("refresh:5;index.php");
}
}
}
else
{
$msg =account already activated
header("refresh:3;index.php");
}
}
else
{
$msg = //no account found
}
}
?>
Thanks a lot!
haha I got it now -_- funny how I suddenly get it right after asking you about it. It's like you're and/or your tutorials are lucky charms XD well anyway, sorry for the bother and thanks a bunch! :)
Deletehello sarah
Deleteglad to hear this, you solved your query right after asking me, thats good :)
keep it up...
Man, this is awesome - you saved my hide!!
ReplyDeletethanks :)
DeleteHey Pradeep, great tutorial!
ReplyDeleteThe activation mail goes out smoothly, but the link in it doesn't seem to activate the account.
What could be wrong?
Thanks!
hello mitko,
Deleteplease check again there's must be some correction on "verify.php" if it redirects from mail then verify.php creates QueryString as "id=something&code=something" like this.
if it not works then let me know the problem ?
SMTP Error: Could not connect to SMTP host.
ReplyDelete×Success! We've sent an email to [email protected]. Please click on the confirmation link in the email to create your account.
i used my gmail credet=endials in phpmailer
iam using in 000webhosting.com....but mail is not receving ........what setting can i change in phpmailer classes and files
please check gmail username, password, and smtp port and try to change SMTPDebug value 0, 1, 2 it will give you error messages with details, and there is no need to do change in phpmailer class
Delete$mail->SMTPDebug = 0;
my this url http://indiawebnet.com/Login-Signup-Email-Verification-Forgot-Password-Script/
ReplyDeletebut your script is not work i am not getting any sineup mailplease hellp me
hello there, first of all please make short and good looking url like this :
Deletehttp://indiawebnet.com/short_folder_name/signup.php
make sure that you have set your SMTP details or not within send_mail() function
$mail->Host = "smtp.yourdomain.com";
$mail->Port = 465;
$mail->Username="[email protected]";
$mail->Password="yourpassword";
$mail->SetFrom('[email protected]','Your Site Name');
Dear sir i agree your opinion but in which php file i putup my mail id [email protected] but i confused about username and password can you suggest me my domain is indiawebnet.com
Deletei have mailed you the code ...
Deletecan you please email me that whole script!
DeleteMany Thank!
please download the script from the given link above :)
Deleteanyone know how to dynamic tabs and pills
ReplyDelete(link- http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_tabs_dynamic&stacked=h )
if any one knows then send me mail please ....
(Thanks)
[email protected]
hello prince, there is a complete source code which create dynamic tabs, download or copy paste that code and try it ....
DeleteAwesome tutorial. Just wanted to say thank you bro. The program is flawless. And for all of you having trouble with "SMTP Error: Could not connect to SMTP host".... Just go to your hosting provider, in cPanel or where ever create an email for your domain, and in the options/management for the email you can find the proper SMTP port and host to add to class.user.php - not hard. Other than that just make sure you change the url for the activation and forgot password and bam.... you're ready to rock.
ReplyDeleteThanks again brother. Maybe you could throw a tutorial up on creating a blog for your website ? Something Im interested in and going to start researching.
-Jordan
thanks :)
DeletePradeep Khodke Thanks first of all. can you please help me that an error is displaying on top of page that "SMTP Error: Could not authenticate." always when i login or signup it is showing that message and iam using my local server. By the way i did not get any email when i signed up or forgot password .. plz help me (email:[email protected])
ReplyDeleteplease check gmail username, password, and smtp port and try to change SMTPDebug value 0, 1, 2 it will give you error messages with details, and there is no need to do change in phpmailer class
Delete$mail->SMTPDebug = 0;
! ) Warning: require_once(mailer/class.phpmailer.php): failed to open stream: No such file or directory in C:\wamp\www\Login\class.user.php on line 112 " thats the error am experiencing
ReplyDeletehello josphat, please check your file path or check there is file or directory exist or not ?
DeleteGot a "NOT FOUND" "The requested URL was not found on this server" once I copied the exact code and set it up and the db connection strings properly. I know the server works cause I have a separate index.html file running on the site thats showing another website. I reached the file structure through a sub folder to separate my code from the code here...any thoughts on where I can start?
ReplyDeleteplease drop an actual and exact error, so that i can help you to solve this issue
Deletethank you pradeep for such a nice tutorial
ReplyDeleteyou're welcome, alex ...
Deletekeep visiting :)
Is it possible to use PHP mailer class with server email address or is this code Gmail only?
ReplyDeleteHello Kristjan, yes we can use this mailer library with server email, just replace gmail credentials with your web mail server details .
DeletePHPH mailer class works like a charm with my virtual server host :)
ReplyDeleteglad it works.. thanks :)
DeleteJordan Again bro. Just curious as to how I would go about adding a confirm password field to the sign up page ? Ive been researching with no luck, cant seem to figure it out. I am new to php. Could you guide me in figuring this out or possibly email me the signup.php file with the required changes implemented and information on what exactly to add to my table so it operates properly? I really do appreciate your time. Thank you. [email protected]
ReplyDeletehello jordan, it's quite simple man,
Deletejust add new input box for confirm password below password box within form and use php and javascript validation to match both passwords
thank you for the code.i'm new to web designing can u tell me how to make the navbar transparent in the home.php page.
ReplyDeleteI tried adding navbar-transparent in the class and wrote
.navbar-transparent {
background:transparent;
background-image: none;
border-color: transparent;
}
in css but didn't work it always remains white.
hello varshik, here is the code i found for you try this one , open following url
Deletehttp://codepen.io/Webspicer/pen/QwvRzM
thanks man,will try this out.
Deletethis tutorial is really helpful
you're welcome, varshik :)
Deletethis is very helpful for beginners..... thanks for sharing the knowledge ;)
ReplyDeletethanks this is very helpful ... your awesome sharing your knowledge for us BIG THAKS FOR U ;)
ReplyDeleteyou're welcome, ricky
Deletekeep visiting :)
hi please hekp me when iam signup the error SMTP Error: Could not authenticate. comes please help me please
ReplyDeleteplease check gmail username, password, and smtp port and try to change SMTPDebug value 0, 1, 2 it will give you error messages with details, and there is no need to do change in phpmailer class
Delete$mail->SMTPDebug = 0;
Nice. Great.
ReplyDeleteSir i have a request.
Can you please de code all functions of wapego.com
like shoutbox with database. Chatroom with db. Upload pic. Profile area. Etc. All wapego.com functions. Thankx
plz give this with new connection of MySQL not with PDO
ReplyDeleteI need some of your expertise please. I am using this script on 1and1 servers. They have PHP mail already enabled. What changes do I need to make to these scripts in order to send email using their servers?
ReplyDeletehello there, you can use this script with your gmail credentials using GMAIL SMTP and if you already have a domain then you can use this script with your smtp domain : smtp.yourdomain.com , you can find your smtp details in your webmail server
Deletehi
ReplyDeletethis what am getting after downloading the code.
SMTP Error: Could not authenticate.
×Success! We've sent an email to [email protected]. Please click on the confirmation link in the email to create your account.
i have not changed anything.how do i solve it .pliz
hi johnson, please check gmail username, password, and smtp port and try to change SMTPDebug value 0, 1, 2 it will give you error messages with details, check it within "class.user.php" within send_mail function
Deletethanks.
Deletewhen i click activate on gmail inbox i get>>> Server Error
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
hello johnson, make sure you have create a directory to store this script and within "signup.php" there is s message variable which have usrl like :
Deletehttp://www.SITE_URL.com/verify.php?id=$id&code=$code
replace SITE_URL with your site name
Hi, Im trying to change database to postgresql and I have problem. I have changed the db config that connects to postgresql but my problem is VERIFICATION.
ReplyDeleteWhen i hit verification link in email the website is white, 0 errors. I have changed the SITE_URL to my host but it still not work.
Anny sugestions?
Hello JA, Please check again your code there's must be some wrong in your code, if you face some issue regarding this then show me your error .
DeleteHello, Pradeep,
ReplyDeleteThanks for your tutorials, but I got this error message,
"SMTP -> ERROR: Password not accepted from server: 534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again."
I'm logged in to my gmail account as I test the code.
I have tried different port, still didn't work.
I don't know how to check which port should I use.
Please help, thanks.
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->AddAddress($email);
$mail->Username="a*****@gmail.com";
$mail->Password="*****";
$mail->SetFrom('[email protected]*.com','Coding Cage');
$mail->AddReplyTo("[email protected]*.com","Coding Cage");
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->Send();
Hello there,
Deleteno need to change this script, it's working, please check again your gmail credentials
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->AddAddress($email);
$mail->Username="[email protected]";
$mail->Password="yourgmailpassword";
$mail->SetFrom('[email protected]','Coding Cage');
$mail->AddReplyTo("[email protected]","Coding Cage");
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->Send();
Oh, one more thing. I searched on Google how to fix that error. I saw this site, https://codingcage.com/2015/09/login-registration-email-verification-forgot-password-php.html . People followed the instruction there and it fixed their problem. I also followed the instruction, but it didn't work. Please help. Thank you.
ReplyDeleteHi
ReplyDeleteIm trying to change the script that will work with PostgreSQL but I have problem. I changed dbconfig.php and connect to new database (this is correct).
Connection +
Insert to db +
Rest -
Cloud You help me, im trying to change user class but poor efects.
Hello JA, this article might help you to connect postgresql
DeletePostgreSQL (PDO) Database Connection
Introduction PostgreSQL (PDO) Database Connection
hi please help SMTP Error: Could not connect to SMTP host.
ReplyDeletehow can i fix it my host is localhost
Hello Aman, I have used here Gmail SMTP to send mails with this you can send mail from your localhost to , so please use your gmail credentials , as per instructions.
DeleteConnection error: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it.
ReplyDeleteI changed the config file but why is it that i am getting the same error?
hello artie, make sure you have started your server or not.
Deletehi pradeep,
ReplyDeletetnx for providing this very helpful tutorial . But i m currently stuck at one place. i tested this script & received the activation link in mail but
after hitting that link for account activation in mail. i received error " sorry ! No Account Found "
pls advise.
Hello pramod, please check in mysql table that the records was inserted or not while registering or check the activation code is same or not with the querystring code in verify.php, if you made some changes in this script then please check your code again, this is working script ;)
DeleteHi Pradeep, both the codes ( token code in database & code showing in emailed activation link) are different.
Deletebut don't know why this happen; as i have not changed the code in verify.php.
pls guide
hello pramod, how the codes are different (token code in database & code showing in emailed activation link)
Deletei have tested this code it's working.
hi pradeep, that's i don't know. pls tell me wht to do now to correct the code.
Deletepls help me out
hi pradeep, pls suggest. wht to do to make this code working as token code in database & code showing in emailed activation link is still showing different
DeleteThanks for this epic tutorial!! - Can you help with one thing please? - I want to get the hang of saving data back to the database. For instance I have crfeated a profile page and can call the username and email.. but how can I save them back to the database if a user wants to amend them? I figure I can have the input field populated with the right data then allow a user to edit it and submit.
ReplyDeleteCan you give an example of saving this user data back to the databas please?
After I enter new password and submit it always redirect to index.php
ReplyDeletehere is page url:http://localhost:8080/mysite/login/resetpass.php?id=aWQ=&code=d5bd351e843c121511eaeb2f40079d89
but for sum reason code can not get the id and Code and redirect to index.php
Any idea why?
Hello Matt, please check your code again if you made some changes in it, i have tested this code, it's working, if not then show me the error.
Delete[EDIT] Sorry if this is a re-post. Not sure if previous one submitted.
ReplyDeleteHi 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.
Hello, thanks a lot for this wonderful script. I've followed your instructions step by step trying to learn the meaning of every single line of code.
ReplyDeleteAll works perfectly but I've a question of a login script feature for you.
I would like to add a "Remember me" checkbox but what I'm doing seems not working properly. On my HTML login form I've put a checkbox in this way:
Remember Me
I had to modify the word "input" in "in-put" due to your comment form that doesn't accept INPUT tag.
On the index.php file I've modified the code in this way:
if(isset($_POST['btn-login']))
{
$email = trim($_POST['txtemail']);
$upass = trim($_POST['txtupass']);
if($user_login->login($email,$upass))
{
$user_login->redirect('home.php');
}
if(isset($_POST['remember'])){
setcookie("cookname", $_POST['txtemail'], time()+60*60*24*100, "/");
setcookie("cookpass", $_POST['txtupass'], time()+60*60*24*100, "/");
}
}
As you can see, related to your code I've added the following strings that should set a cookie for 100 days:
if(isset($_POST['remember'])){
setcookie("cookname", $_POST['txtemail'], time()+60*60*24*100, "/");
setcookie("cookpass", $_POST['txtupass'], time()+60*60*24*100, "/");
}
Obviously, it doesn't work...could you help me please on solving this little trouble? And, of course, if you want you can update your tutorial with this new feature.
Thanks for all.
Pradeep, clean script but many things have to implement related to security point of view. First secure your password using this small but powerfull script:
ReplyDelete$new_pass = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);
Note ['cost' => may change to any integer ex: 12 / 17 / 23 ..... ]
thanks aamir for the suggestion, and sorry for the late reply :)
DeleteHello, I use unicode font, I have problem data is written in database with symbols: "ბუიღლიშვილი" Where and what should I write to prevent this?
ReplyDeleteHello Levan, this article might help your : PHP MySQL Unicode
DeleteHi, thank you for the tutorial! I modified a bit of the code if that is alright. Again thank you for taking the time to create the tutorial.
ReplyDeletethanks sven, keep visiting :)
DeleteHello!! I need some help. When I sign up I receive an error message, Server error 500. Data is saved correctly, but I'm having the same error. Could someone help me?
ReplyDeleteHello!! I need some help. When I sign up I receive an error message, Server error 500. Data is saved correctly, but I'm having the same error. Could someone help me?
ReplyDeletehello sandra, have you add any other file with this script like htaccess ...
DeleteHey I'm getting an error at trying to register an account
ReplyDeleteFatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in C:\xampp\htdocs\register.php:20 Stack trace: #0 C:\xampp\htdocs\register.php(20): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\register.php on line 20
Hello I'm having an error, Can you help me?
ReplyDeleteFatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in C:\xampp\htdocs\register.php:20 Stack trace: #0 C:\xampp\htdocs\register.php(20): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\register.php on line 20
Hello Gabriel, please make sure that database is properly selected or not it shows "No database selected"
DeleteHello, can you please help me.Am getting this error on user.php file :
ReplyDeleteFatal error: Call to a member function prepare() on a non-object
What could be wrong?
Hi cool tutorial, but i can't start... i have this error.(
ReplyDeleteFatal error: Call to undefined method PHPMailer::SetFrom() in /users/******/www/php_reg_Login/class.user.php on line 124
this ist the script../class.user.php
_______________________________________________________________________
function send_mail($email,$message,$subject)
{
require_once('class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->AddAddress($email);
$mail->Username="******@gmail.com";
$mail->Password="*******";
$mail->SetFrom('*******@icloud.com','Coding Cage');
$mail->AddReplyTo("******@icloud.com","Coding Cage");
$mail->Subject = $subject;
$mail->MsgHTML($message);
$mail->Send();
}
}
__________________________________________________________________________________________
i have no idea how to do...chch i have try f***** 4hours (haha) to get it to work....hard shit.
You are a damn good, i have much to learn...include english. lol Peace
Hello there, sorry for the late reply, did you solved this ? let me know.
DeleteHi...no luck!!..i have downloaded you dropbox zip...thank you :)
DeleteSomthing is better and working, other not.I can register me, but i cant activat via email. i dont recive email..
this is the error i have:
SMTP -> FROM SERVER:220 smtp.gmail.com ESMTP 75sm32687437wmo.22 - gsmtp
SMTP -> FROM SERVER: 250-smtp.gmail.com at your service, [148.251.48.69] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8
SMTP -> ERROR: Password not accepted from server: 534-5.7.9 Application-specific password required. Learn more at 534 5.7.9 https://support.google.com/accounts/answer/185833 75sm32687437wmo.22 - gsmtp
SMTP -> FROM SERVER:250 2.1.5 Flushed 75sm32687437wmo.22 - gsmtp
SMTP Error: Could not authenticate.
good new year @all
thank you for the tutorial ,but i can't download full project
ReplyDeletepleas upload it to dropbox or mediafire.
i upload this script to dropbox get it from there : download here
Deletethe site provided for downloading code. is not delivering the file to download
ReplyDeleteHello Saikat, sorry for the inconvenience, get this script from here : download here
Deletei have a problem with "SMTP Error: Could not authenticate."
Deleteand i have putted my gmail details to /class.user.php file under send_mail()
but the problem remains same.
is there any change has to be made in //mailer/class.smtp.php file??
if yes then what will be the change .if other change needed please specify.
and there in //mailer/class.smtp.php file you have not specified any host just said that if its empty then it will be local host. and port is 25.
Deleteis that ok there or i have to change this? or any other..
i have created a new gmail account. Now is working fine:) smtp errors was come from a old gmail. account that i had used before. tss chch lol...
ReplyDeleteSuper, now its save the password in the db and i can log me in with that password. the verification e-Mail, is working fine. But i have one problem...argh! I miss the activation e-Mail, for the new password...sorry my bad english
"learning by doing!!! )" Edgar
Fatal error: Class 'SMTP' not found in C:\xampp\htdocs\mailer\class.phpmailer.php on line 1325
ReplyDeleteSMTP -> FROM SERVER:220 smtp.gmail.com ESMTP s129sm33517920wmf.18 - gsmtp
ReplyDeleteSMTP -> FROM SERVER: 250-smtp.gmail.com at your service, [193.2.186.194] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8
SMTP -> ERROR: Password not accepted from server: 534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 s129sm33517920wmf.18 - gsmtp
SMTP -> FROM SERVER:250 2.1.5 Flushed s129sm33517920wmf.18 - gsmtp
SMTP Error: Could not authenticate.
help me please... i tried everything and still this message ,,
Worth sharing this issue I had using the gmail setup and the fix
ReplyDeleteSMTP Error: Could not authenticate.
The thing which fixed it for me was from this link http://stackoverflow.com/questions/20337040/gmail-smtp-debug-error-please-log-in-via-your-web-browser
In the event in the future if that link is busted here is a copy of it
Head over to Account Security Settings (https://www.google.com/settings/security/lesssecureapps) and enable "Access for less secure apps", this allows you to use the google smtp for clients other than the official ones.
Hello Scott,
Deletethanks for sharing this issue it will help others as well to solve theirs.
SMTP Error: Could not authenticate.
ReplyDeleteHello Achille, please make sure you have given proper gmail credentials ...
Deleteyou can look at the just above comment by @scott.
DeleteHi PRADEEP, thx for your time and this tutorial. It works fine, PHPMailer with other Provider as google works too. Can i combine the code from tutorial "PHP Login and Registration Script with PDO and OOP"? I would like toexchange md5() for password_hash() / password_verify(). Greatings from Germany, Jan.
ReplyDeleteHello Jan, of course you can add new password hashing function on this script, just do what i have done on that script for password hashing
Deletethanks for visiting :)
Hi PRADEEP, i got it :-), it works. Only 'resetpass.php' generated al "clear name password"(?) in database. It must hashed before insert in database. Great tutorial and many thanks. I raise my glass german beer to you :-) Jan
ReplyDeleteYes It's must be hashed with new password hashing functions, well i have just focused here on email activation and forgot password.
DeleteHi Pradeep!
ReplyDeleteFirst of all: Great job! Code works like a charm for me except one little thing: The message is fine, but the header and the title of the activation e-mail, sent by the mailer has encoding issues for me. I checked the encoding of the files, and I set a meta tag charset=utf-8 on the html side but had no luck... after that, tried to force the files signup and user class with this "header('Content-type: text/html; charset=utf-8');" header to utf-8 but had no luck again...can u help me with this?
Oh and one more question: This code is under MIT?
Thnx for your nice tutorial. i m facing a problem. when i clicking on the action link blank page are coming and the url is like this http://localhost/x/verify.php?id=NA==&code=5d98324ce5ea352f34ad44a51e86ad4f. Hiw can i solve this issue?
ReplyDeleteThnx a lot for ur nice tutorial.I m facing a prb. When i m clicking on the activate button for account confirmation i am getting a blank page and my url is like this. http://localhost/x/verify.php?id=NA==&code=5d98324ce5ea352f34ad44a51e86ad4f. How can i solve this?
ReplyDeletevery nice code php
ReplyDeleteI love this script but it has 1 flaw, I have had a lot of users mention that sometimes they don't receive the activation email.
ReplyDeleteHow would I add a "Resend Verification Email" into this?
Kind regards
Jamie
I want to thank the coder for this awesome tutorial and coding, very educational or a beginner like me.
ReplyDeleteJust one question:
On the "signup.php" I would like to add another option for it to look like this:
Username:
E-Mail Address
Password:
User Code:
The user code is the code that I would provide to the person that i want to grant access to the website. Once they enter all info and the assigned code, it will send them the activate e-mail.
If anyone else tries to sign up but does not enter the assigned code that was previously given to them, they will not be granted access to the home page and not able to register and then take them back to the main index.php page.
How can I accomplish this?
I have a code number on MySQL:
7 Codenum varchar(10) latin1_swedish_ci No 123456789
Can anyone help on this?
Thank you in advance.
You must provide at least one recipient email address.
ReplyDelete× Success! We've sent an email to [email protected]. Please click on the confirmation link in the email to create your account... any help?
Wow Pradeep your amazing
ReplyDeleteit works yay!!!!!!!!
been trying to suss this out for a year...
just for those who were confused
Goto class.usser.php file
and change line 121-124 changing your details
The last bit Im confused with is the authentication
I believe the line we need to alter is in the file signup.php
line 47
Click HERE to Activate :)
if my website is www.jessabella.com
what should line 47 be so that the authentication is updated
how does it actually work
does my site have to have something enabled to recieve this message and update my users records
many thanks
Jess :)
Wow again!!!!!!! Pradeep you are amazing!!!!!!!
ReplyDeleteokay got it...regarding the verification
so for this line
Click HERE to Activate :)
in signup
if as you say its on local host, the x will be the name of the folder within the htdocs
which would be the same as for a site hosted somewhere on the actual web
wow my minds blown
soooooooooooooooooo happy thank you Pradeep your tutorials are the best ever
thanks from
Jessa
I'm receiving the following error: Connection error: could not find driver. Any help would be appreciated.
ReplyDeleteConnection error: could not find driver
ReplyDeletepublic $Host = 'smtp.gmail.com';
ReplyDelete/**
* Sets the default SMTP server port.
* @var int
*/
public $Port = 587;
/**
* Sets the SMTP HELO of the message (Default is $Hostname).
* @var string
*/
public $Helo = '';
/**
* Sets connection prefix.
* Options are "", "ssl" or "tls"
* @var string
*/
public $SMTPSecure = 'tls';
/**
* Sets SMTP authentication. Utilizes the Username and Password variables.
* @var bool
*/
public $SMTPAuth = true;
/**
* Sets SMTP username.
* @var string
*/
public $Username = '[email protected]';
/**
* Sets SMTP password.
* @var string
*/
public $Password = 'secret';
And it`s not working... i get SMTP Error: Could not authenticate.
My Email is hosted at gmail.
ReplyDeleteFatal error: Call to undefined method PHPMailer::SetFrom() in C:\xampp\htdocs\Rebellion\Class.User.php on line 123 this keeps showing.. why?? can you fix it?
Hi Pradeep,
ReplyDeleteYour code is working perfectly, and I am new to php and learning from your tutorials
But I think I have got an issue in resetpass.php file,
In this file when someone type password it actually posting and saving row data not with md5 encryption. infact there is no code for md5 encryption
Please check and update the code in your website
Thank you
Hi,
ReplyDeleteMy update on resetpass.php
I have added this code and it is working, thanks again
$newpass = md5($cpass);
$stmt = $user->runQuery("UPDATE tbl_users SET userPass=:upass WHERE userID=:uid");
$stmt->execute(array(":upass"=>$newpass,":uid"=>$rows['userID']));
SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
ReplyDeleteSMTP Error: Could not connect to SMTP host.
Success! We've sent an email to [email protected]. Please click on the confirmation link in the email to create your account.
There are no problem when I test it on my localhost, But when I try to use it on my domain that problem above occurred
Database connection is normal, the user account is created, the problem is only because it's SMTP timeout and the email is not being sent.
The credential are all OK
I'm only not sure about the port, btw how to looked at the port, is different domain hosting server use different port for SMTP?
SMTP -> ERROR: Failed to connect to server: Connection timed out (110)
ReplyDeleteSMTP Error: Could not connect to SMTP host.
Success! We've sent an email to [email protected]. Please click on the confirmation link in the email to create your account.
There are no problem when I test it on my localhost, But when I try to use it on my domain that problem above occurred
Database connection is normal, the user account is created, the problem is only because it's SMTP timeout and the email is not being sent.
The credential are all OK
I'm only not sure about the port, btw how to looked at the port, is different domain hosting server use different port for SMTP?
Hi. Very great tutorial. Best what i have seen. But my hosting is blocking all outgoing smtp connections. I see, that there is option, to send emails with sendmail. Could you tell please, how to enable this option?
ReplyDeleteHi. It is best tutorial what i have seen. My hosting is blocking all outgoing smtp connections. How i can send emails with sendmail? I see, that this option is available in script, but i dont know how to enable this.
ReplyDeleteGood job PRADEEP!!, a question for which values are
ReplyDelete"INSERT INTO `tbl_users` (`userID`, `userName`, `userEmail`, `userPass`, `userStatus`, `tokenCode`) VALUES
(1, 'gautam', '[email protected]', '202cb962ac59075b964b07152d234b70', 'N', 'a91f7123ffe33f224a7592f923bb141a');"
Thanks
Hi
ReplyDeleteNice code and nice tuto !
Where add session_regenerate_id(true) in the code?
Please could you improve this for such a noob like me ?
I upload the file via FTP, make table in phpmyadmin, configuring dbconfig.php but the script dont work. Look at : http://mluci.com/platforma
ReplyDeleteHello Lucian, what's the query/error,
DeleteThanks so much for all of your article,. I am just new on php, mysql, html, and css,. your website is helpful
ReplyDeleteHello Jimmi,
DeleteGlad you liked it, you can subscribe us to get new content's in your inbox.
Hi,i have a problem
ReplyDeleteWarning: require_once(mailer/class.phpmailer.php): failed to open stream: No such file or directory in C:\xampp\htdocs\coba\class.user.php on line 112
Fatal error: require_once(): Failed opening required 'mailer/class.phpmailer.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\coba\class.user.php on line 112
What happen ?
Hi what should i do with this?
ReplyDeleteFatal error: Class 'SMTP' not found in C:\xampp\htdocs\coba\class.phpmailer.php on line 1321
Hello Ayu
Deleteplease make proper directory/folder for the script, class.phpmailer.php file shoud be in mailer folder
not this : C:\xampp\htdocs\coba\class.phpmailer.php
should be : C:\xampp\htdocs\coba\mailer\class.phpmailer.php
and in class.user.php within send_mail function include like this
require_once('mailer/class.phpmailer.php');
i already make mailer folder. but the comment still like this
DeleteFatal error: Class 'SMTP' not found in C:\xampp\htdocs\coba\mailer\class.phpmailer.php on line 1321
did you make some changes in this script, hence it is working i have tested it.
Deletei just copy n paste all the source and for mailer/class.phpmailer.php i copy from here : http://sourceforge.net/projects/phpmailer/.
DeleteIn class.user.php :
$mail->AddAddress($email);
$mail->Username="[email protected]"; (here i change with my gmail id)
$mail->Password="yourgmailpassword"; (here i change with my password)
$mail->SetFrom('[email protected]','Coding Cage');(how about here?should i change or not?)
$mail->AddReplyTo("[email protected]","Coding Cage");(and how about this?)
$mail->Subject = $subject;
So,i change gmail id and password, is that the problem?
i have given all the files, so you don't need to get code from sourceforge. there are only three files in mailer folder.
Deletehi again,now when i run the progra it is looking good, when i try sign up, there is a note say:Success! We've sent an email to [email protected]. Please click on the confirmation link in the email to create your account. but i can't delete that message when i click X button. And when i checked mymail, there is no email in inbox about confirmation link. So i check phpmyadmin,the status still N because i'm not clicking confirmation yet. So i just change become Y manually in phpmyadmin and try login, but when i press login, it still in login page and not go to home.php. And the error warning is SMTP Error: Could not authenticate.
DeleteIn class.user.php :
$mail->Username="[email protected]"; (here i change with my gmail id)
$mail->Password="yourgmailpassword"; (here i change with my password)
$mail->SetFrom('[email protected]','Coding Cage');(i change with gmail id same as above)
$mail->AddReplyTo("[email protected]","Coding Cage");(i change with gmail id same as above)
What happen ?
Hello Sir!
ReplyDeleteHere's my error..
"SMTP Error: Could not connect to SMTP host"
how to check gmail credential????
i m running on my local server (apache)...
PLs help me
Hi Hebron,
DeleteYour Gmail Credentials are your gmail id/password, that's it...
this cool. like it thanks..
DeleteDoesn't work. SMTP Error: Could not authenticate. I don't know, what I have to fill in.. It is too much..
ReplyDelete