Mail reset password link using php

hii all,
i’m developing a script that emails a random link to user’s email when an user has forgotten his/her password.,
the problem is, i want to insert a random key in my database key column against the same user who has clicked forgot password link, after inserting the same i should invoke php mail to send the URL who has lost password…
now after running the below script on my server, i can see URL in plain text printed same as in the script. can anyone please help me, how to achieve those 2 operations(inserting a random key into DB against an user who clicks forgot password, email valid URL to user)…

here is my script;

<?php
 session_start();

 //Connect to mysql server
	$link=mysql_connect("localhost","root","");
	if(!$link) {
		die('Failed to connect to server: ' . mysql_error());
	}
	//Select database
	$db=mysql_select_db("blackerdread");
	if(!$db) {
		die("Unable to select database");
	}

 if(!get_magic_quotes_gpc())
 {
	$row['customerID'] = stripslashes($_POST[$row['customerID']]);
 }else{
	$row['customerID'] = $_POST[$row['customerID']];
	
 }



	 $key = substr(base64_encode(crypt('', '')), 0, 32);
    $query1="INSERT INTO ss_customers (key) VALUES ('$key') WHERE customerID='8'";
	 $result1=mysql_query($query1);
	 echo $query1;
	 exit();
	 $query = "SELECT Login, Email FROM ss_customers WHERE customerID='8'";
	  $result=mysql_query($query);
	  $row = mysql_fetch_array($result);
		  if(mysql_num_rows($result)>0)
			{
			$Email = $row['Email'];
			$Login = $row['Login'];
			$headers4="admin@blackerdread.com"; // Change this address within quotes to your address
            $headers.="Reply-to: $headers4\
";
            $headers .= "From: $headers4\
";
            $headers .= "Errors-to: $headers4\
";


// mail funciton will return true if it is successful
if(mail("$Email","Your Request for login details","This is in response to your request for login detailst at site_name \
 \
Login ID: $Login \
 URL . resetpassword.php?page=reset-password&Login= . urlencode($Login) . &key= . urlencode($key) . \\r\
 . \
\
 Thank You \
 \
 siteadmin","$headers")){echo "<center><font face='Verdana' size='2' ><b>THANK YOU</b> <br>Your password is posted to your emil address . Please check your mail after some time. </center>";}
else{// there is a system problem in sending mail
echo " <center><font face='Verdana' size='2' color=red >There is some system problem in sending login details to your address. Please contact site-admin. <br><br><input type='button' value='Retry' onClick='history.go(-1)'></center></font>";}
	}
	else {
		echo "mail not sent";
	}
			






What happens when you run this script?

What happens when you run this script?

when i run this script, an email has been sent with URL as plain text

URL . resetpassword.php?Login= . urlencode($Login) . &key= . urlencode($key) .

in place of $Login, LoginID of the user and in place of $key a key were generated.
and moreover, i dont see any key inserted into the DB.
what i require is, when the user enters correct details like secret question, then a random key should be generated then inserted into the DB against a particluar user ROW, and an email has to be sent to the same user containg the key in URL.

i hope you understand…
many thanks for the comeback.

<?php

$key = substr(base64_encode(crypt('', '')), 0, 32);
$key = mysql_real_escape_string($key);
$query1="UPDATE ss_customers SET key = ('{$key}') WHERE customerID='8'";   

Try that

hii…

PHP Code:

<?php

$key = substr(base64_encode(crypt(‘’, ‘’)), 0, 32);
$key = mysql_real_escape_string($key);
$query1=“INSERT INTO ss_customers (key) VALUES (‘{$key}’) WHERE customerID=‘8’”;

Try that

yes, i tried that… but i cannot see any key inserted into the DB…
thats fine, i’ve a doubt now regarding URL parameters…
now i need to GET those parameters which i’m sending to a particular user via URL.
$URL. “resetpassword.php?Login=” . urlencode($Login) . "&key=$key
"

after clicking the above URL, user will be shown a password update form, after entering passwords correctly, form action for the resetpassword page is updatepassword, where in update password page, i need to check for Login in DB and matches it with URL’s Login then if both are validated then the password will be updated else an error message “your userid not matched with the URL”

how to get parameters from that URL and match them with DB??
here is my resetpassword.php code

<?php
session_start();
$Login = $_GET['Login'];
//echo $Login;
//exit();
$customerID = $_GET['customerID'];
$Login = $_SESSION[$_GET['Login']];

?>
<HTML>
<HEAD>

<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; CHARSET=UTF-8">
<META HTTP-EQUIV="CONTENT-SCRIPT-TYPE" CONTENT="text/javascript">

<TITLE>Password Change Form</TITLE>
<script>

form_submitted=false
function ValidationError(form, Invalid, error_message, focus)
{
	alert(error_message)
	if(form[focus].focus)
		form[focus].focus()
}

function ValidateForm(theform)
{
	var e='There were problems with your input:\
\
', i={}, f='', r, s
	
	r=theform['newpassword']
	r.className=''
	r=theform['confirm']
	r.className=''
	
	 if(!i['newpassword']
	&& (theform['newpassword'].value==''))
	{
		r=theform['newpassword']
		r.className='invalid'
		if(e=='There were problems with your input:\
\
')
			f='newpassword'
		else
			e+='\
\
'
		e+=(i['newpassword']='==> Please enter your new password.')
	}
		if(!i['newpassword']
	&& ((theform['newpassword'].value.search
	&& theform['newpassword'].value.search(new RegExp('^[a-zA-Z]','g'))==-1)))
	{
		r=theform['newpassword']
		r.className='invalid'
		if(e=='There were problems with your input:\
\
')
			f='newpassword'
		else
			e+='\
\
'
		e+=(i['newpassword']='==> The new password must start with a letter.')
	}

		if(!i['newpassword']
	&& (theform['newpassword'].value.length<8))
	{
		r=theform['newpassword']
		r.className='invalid'
		if(e=='There were problems with your input:\
\
')
			f='newpassword'
		else
			e+='\
\
'
		e+=(i['newpassword']='==> The Password must contain atleast 8 characters.')
	}
		if(!i['newpassword']
	&& (theform['newpassword'].value.length>14))
	{
		r=theform['newpassword']
		r.className='invalid'
		if(e=='There were problems with your input:\
\
')
			f='newpassword'
		else
			e+='\
\
'
		e+=(i['newpassword']='==> The Password must not exceed 15 characters.')
	}
		 if(!i['confirm']
	&& (theform['confirm'].value==''))
	{
		r=theform['confirm']
		r.className='invalid'
		if(e=='There were problems with your input:\
\
')
			f='confirm'
		else
			e+='\
\
'
		e+=(i['confirm']='==> Please enter your confirmation password.')
	}
		if(!i['confirm']
	&& (theform['confirm'].value!=theform['newpassword'].value))
	{
		r=theform['confirm']
		r.className='invalid'
		if(e=='There were problems with your input:\
\
')
			f='confirm'
		else
			e+='\
\
'
		e+=(i['confirm']='==> Passwords do not match.')
	}

if(e!='There were problems with your input:\
\
')
	{
		ValidationError(theform, i, e, f)
		form_submitted=false
		return false
	}
	return true
}
	</script>
</HEAD>
<body BGCOLOR="#FFFFFF" TEXT="#252525" VLINK="#990000" ALINK="#990000" LINK="#990000" onload="document.forms['changepassword']['password'].focus()" >

<BR>
<TABLE WIDTH="770" BORDER="0" CELLSPACING="2" CELLPADDING="4" ALIGN="CENTER" >

<TR>
<TD>
<P CLASS="headerbanner">
Password Change Form
</P>

<FORM NAME="changepassword" METHOD="POST"
ACTION="updatepassword.php" onsubmit="return ValidateForm(this)">

<TABLE CELLPADDING="2" ALIGN="CENTER"
SUMMARY="Secondary table holds input fields and buttons" >


<TR>
<TD CLASS="text">
<SPAN STYLE="font-weight: bold;" >
New Password:
</SPAN>
<BR>
<INPUT TYPE="PASSWORD" CLASS="password" NAME="newpassword" MAXLENGTH="15" SIZE="30">

</TD>
</TR>
<TR>
<TD CLASS="text">
<SPAN STYLE="font-weight: bold;">
Confirm New Password:
</SPAN>
<BR>
<INPUT TYPE="PASSWORD" NAME="confirm"  MAXLENGTH="15" SIZE="30">
</TD>
</TR>
</TABLE>
<BR>
<CENTER>
<button type="submit" align="center" OnMouseover="window.status='Change Password';return true;" OnMouseout="window.status=' ';"/><img src="http://localhost/MyDreamProject/images/pwd.gif" alt=""/>
Save Password-></button>&nbsp;

<button type="reset" align="center" OnMouseover="window.status='Refresh Page';return true;" OnMouseout="window.status=' ';"/><img src="http://localhost/MyDreamProject/images/refresh.png" alt=""/>
Reset</button>
</CENTER>


</TD>
</TR>
</FORM>
</TABLE>
<div id='DetachDiv' height=0 width=0 frameborder=0></div>
</BODY>
</HTML>

here’s my update password.php (form action script for resetpassword.php page)

<?php
   session_start();

$Login = $_GET['Login'];
//echo $Login;
//exit();

//Connect to mysql server

$link=mysql_connect("localhost","root","");

if(!$link) {

die('Failed to connect to server: ' . mysql_error());

}

//Select database

$db=mysql_select_db("blackerdread");

if(!$db) {

die("Unable to select database");

}
 if(!get_magic_quotes_gpc())
 {
$Login = stripslashes($_POST['Login']);
$row['customerID'] = stripslashes($_POST[$row['customerID']]);
$newpassword = stripslashes($_POST['newpassword']);
$confirm = stripslashes($_POST['confirm']);
 }else{
$Login = $_POST['Login'];
$row['customerID'] = $_POST[$row['customerID']];
$newpassword = $_POST['newpassword'];
$confirm = $_POST['confirm'];
 }
$encrypt1 = base64_encode($newpassword);
//echo $encrypt1;
//$decode = base64_decode($encrypt1);
//echo $decode;
//exit();

$key = $_POST['key'];

$query1 = "select Login FROM ss_customers WHERE key='".$_SESSION['key']."' and Login='".$Login."'";
$result = mysql_query($query);

if($newpassword == $confirm)
{
$query = "UPDATE ss_customers Set cust_password='$encrypt1' where Login='".$Login."'";
$result = mysql_query($query);
//echo $query;
//exit();
//update the password in the session so you don't have to logoff
//$_SESSION["password"] = $encrypt1;
//echo an confirm.
echo "password updated";
exit;
}
else{
echo "you are not authorized to change passowrd!";
exit;
}
?>


my task will be completed if i can match URL’s login with the DB login and URL’s key with DB’s key…
can you please suggest me…
many thanks for the comeback.

my task will be completed if i can match URL’s login with the DB login and URL’s key with DB’s key…
can you please suggest me…
many thanks for the comeback.

Hii…
i matched those URL parameters with DB by getting them from URL. it is working now…
but MYSQL insert query is not working…
but the only problem is with my INSERT query, in which i’m trying to insert a randomly generated KEY into the DB against a particular USER and send it via an URL…
when user clicked that link, i need to perform 2 validations there by getting URL parameters, LOGINID and KEY with the DB records…
can you please suggest me how can do this?

please let me know can we add a single column for an existing table and insert a value into it?
presently my INSERT query is like this…

$key = substr(base64_encode(crypt('', '')), 0, 32);
	 $key = mysql_real_escape_string($key);
     $query1="INSERT INTO ss_customers (key) VALUES ('{$key}') WHERE customerID='".$_SESSION['customerID'] ."'";
	 $result1=mysql_query($query1);
echo $query1;
exit();

i tried many times, but the key is not being inserted into the DB against a particluar ROW.
what i need to do is, after inserting a key into the DB, send an URL to user’s email, then match DB’s LOGIN ID and KEY with URL GET paramaeters, if both are same then update password else Invalid LINK…
please do suggest me…
many thanks…
please suggest me how to proceed now…

hi all…

i’m generating a KEY and trying to insert it into the database, but it is not being inserted. my table has already 12 columns, i added another column “KEY” of type VARCHAR and of size 100.

the query is :

$key = substr(base64_encode(crypt('', '')), 0, 32);
	 $key = mysql_real_escape_string($key);
     $query1="INSERT INTO ss_customers (key) VALUES '".$key."' WHERE customerID='".$_SESSION['customerID'] ."'";
	 $result1=mysql_query($query1);
	 echo $query1;
	 exit();

when i print the query, i can see the KEY value. but i cannot see any row filled up in my database…
can anyone please help me… can we use WHERE clause in INSERT query?
PS: The KEY is dynamically generated, it is not coming from any other form…

here is the general procedure for debugging a mysql error in your php code –

echo out the sql statement with all php variables substituted with real values, then run the query outside of php, i.e. right in mysql

this will give you the exact mysql error message

:slight_smile:

in your case, it’s because the INSERT statement does not allow a WHERE clause

INSERT inserts a complete new row, so a WHERE clause makes no sense whatsoever

i suspect that what you might want to try is UPDATE instead of INSERT

hello sir,

echo out the sql statement with all php variables substituted with real values, then run the query outside of php, i.e. right in mysql

in your case, it’s because the INSERT statement does not allow a WHERE clause

INSERT inserts a complete new row, so a WHERE clause makes no sense whatsoever

i suspect that what you might want to try is UPDATE instead of INSERT

Yes, absolutely…
i’ve to use UPDATE query instead of INSERT query. i replaced INSERT with UPDATE… KEY column in my table is not null, i doubt whether the values get updated or not?
shall i make it NULL, so that “0” can be overwritten with $key value…?

i tried the same in MYSQL.
i’m got the following error…

[B]Error

SQL query:

“UPDATE ss_customers Set key=‘JDEkMnUxLmhOLi4kZllsSUJicUZCclZP’ WHERE customerID=‘8’”

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘"UPDATE ss_customers Set key=‘JDEkMnUxLmhOLi4kZllsSUJicUZCclZP’ WHERE customerID’ at line 1 [/B]

key is a reserved word so you must use back ticks, that could be your problem.


UPDATE ss_customers Set `key` ='JDEkMnUxLmhOLi4kZllsSUJicUZCclZP' WHERE customerID='8'

the sql query should not be enclosed in quotes – that actually turns the query into a big long string

key is a reserved word so you must use back ticks, that could be your problem.

SQL Code:

UPDATE ss_customers SET key ='JDEkMnUxLmhOLi4kZllsSUJicUZCcl

Absolutely, That worked! :slight_smile: Great… i didnt thought about this, ive been exploring the query…
Thanks alot oddz…
thanks for all who helped me in fixing my bug…