In many websites we will see option like ‘forgotten password’, this will help us to recover password of users. If we click on forgotten password option,you’ll be redirected to a form details where you will have to check your username or email. These details are being send in the database to check if the user address really exists. If so, then you’ll receive in your email address an automatic response from the database with the new password details.
View Final DemoDownload
Step 1 – THE HTML
The first step is to make the connection between the database and mysql using the web application given in the file dbc.php .
<!--?php
define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", "user"); // set database user
define ("DB_PASS","pass"); // set database password
define ("DB_NAME","dbname"); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
/* Registration Type (Automatic or Manual)
1 ---> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 1; // set 0 or 1
define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password
//define ("ADMIN_NAME", "admin"); // sp
/* Specify user levels */
define ("ADMIN_LEVEL", 5);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);
function page_protect() {
session_start();
global $db;
/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
logout();
exit;
}
}
// before we allow sessions, we need to check authentication key - ckey and ctime stored in database
/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['id_user']) && !isset($_SESSION['Nom']) )
{
if(isset($_COOKIE['id_user']) && isset($_COOKIE['Password'])){
/* we double check cookie expiry time against stored in database */
$cookie_user_id = filter($_COOKIE['user_id']);
$rs_ctime = mysql_query("select `ckey`,`ctime` from `user` where `id_user` ='$cookie_id_user'") or die(mysql_error());
list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
// coookie expiry
if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {
logout();
}
/* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/
if( !empty($ckey) && is_numeric($_COOKIE['id_user']) && isUserID($_COOKIE['Nom']) && $_COOKIE['user_key'] == sha1($ckey) ) {
session_regenerate_id(); //against session fixation attacks.
$_SESSION['id_user'] = $_COOKIE['id_user'];
$_SESSION['Nom'] = $_COOKIE['Nom'];
/* query user level from database instead of storing in cookies */
list($user_level) = mysql_fetch_row(mysql_query("select user_level from user where id_user='$_SESSION[id_user]'"));
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
} else {
logout();
}
} else {
header("Location: index.php");
exit();
}
}
}
function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}
function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}
function ChopStr($str, $len)
{
if (strlen($str) < $len)
return $str;
$str = substr($str,0,$len);
if ($spc_pos = strrpos($str," "))
$str = substr($str,0,$spc_pos);
return $str . "...";
}
function isEmail($email){
return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}
function isUserID($Nom)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $Nom)) {
return true;
} else {
return false;
}
}
function isURL($url)
{
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
return true;
} else {
return false;
}
}
function checkPwd($x,$y)
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }
if (strcmp($x,$y) != 0) {
return false;
}
return true;
}
function GenPwd($length = 7)
{
$password = "";
$possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function GenKey($length = 7)
{
$password = "";
$possible = "0123456789abcdefghijkmnopqrstuvwxyz";
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function logout()
{
global $db;
session_start();
if(isset($_SESSION['id_user']) || isset($_COOKIE['id_user'])) {
mysql_query("update `user`
set `ckey`= '', `ctime`= ''
where `id_user`='$_SESSION[id_user]' OR `id_user` = '$_COOKIE[id_user]'") or die(mysql_error());
}
/************ Delete the sessions****************/
unset($_SESSION['id_user']);
unset($_SESSION['Nom']);
unset($_SESSION['user_level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy();
/* Delete the cookies*******************/
setcookie("id_user", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("Nom", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("Password", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
header("Location: index.php");
}
// Password and salt generation
function PwdHash($pwd, $salt = null)
{
if ($salt === null) {
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else {
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($pwd . $salt);
}
function checkAdmin() {
if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}
}
?>
Step 2 – File : forgotten Password.php
Second, Input the code before tag html
<!--?php
include 'dbc.php';
/******************* ACTIVATION BY FORM**************************/
if ($_POST['doReset']=='Reset')
{
$err = array();
$msg = array();
foreach($_POST as $key =--> $value) {
$data[$key] = filter($value);
}
if(!isEmail($data['email'])) {
$err[] = "ERROR - Please enter a valid email";
}
$user_email = $data['email'];
//check if activ code and user is valid as precaution
$rs_check = mysql_query("select id_user from user where email='$user_email'") or die (mysql_error());
$num = @mysql_num_rows($rs_check);
// Match row found with more than 1 results - the user is authenticated.
if ( $num <= 0 ) {
$err[] = "Error - Sorry no such account exists or registered.";
//header("Location: forgot.php?msg=$msg");
//exit();
$rows = @mysql_fetch_array($rs_check);
$Your_Password = $rows['Password'];
}
if(empty($err)) {
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
//send email
$retour = @mysql_query('SELECT Password FROM user');
$message = "Here are your Password details ...\n";
$message .= " Your Username :\t$Nom\n";
$message .= " Your Password :\t$your_password\n";
mail($user_email,"Reset Password", $message, "From: \"Member Registration\" <auto-reply@$host>\r\n" . "X-Mailer: PHP/" . phpversion());
$msg[] = "you can modify it following the link in your email.";
//$msg = urlencode();
//header("Location: forgot.php?msg=$msg");
//exit();
}
}
?>
</auto-reply@$host>
Step 3 – Javascript
Third, put the code between the tag head
<script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate();
});
</script>
Step 4 – The HTML Form
<h2 class="title"><a href="#"><strong>Forgotten Password</strong> !</a></h2>
<form method="post" action="Forgot Password.php" class="registration_form">
<fieldset>
<p>
<label for="email">Email Address :</label></p>
<p>
<input name="email" type="text" id="email" size="30">
</p>
<input type="submit" name="doReset" id="doLogin3" value="Reset">
</fieldset>
</form>
Finaly Clic Here