PHP - Why Reset Password Wont Work?
Hi
I have the code below when users firget their password, they fill forrgot password form and an email will be sent to them which directs them to a page where (code below) they can reset their password. When i fill the form I get the msg it says password has been changed however it wont change it in database. I have checked the code, current entries in database etc but still it wont change the password. Can u please what im doing wrong? <?php include 'global.php'; $account_reference = $_GET['code']; echo "$account_reference"; if (isset($_POST['resetpassword']) && $_POST['resetpassword']) { $email = addslashes(strip_tags($_POST['email'])); $username = addslashes(strip_tags($_POST['username'])); $password = addslashes(strip_tags($_POST['password'])); $newpasswordnomd = addslashes(strip_tags($_POST['newpassword'])); $repasswordnomd = addslashes(strip_tags($_POST['repassword'])); $code = addslashes(strip_tags($_POST['code'])); $getdata=mysql_query("SELECT * FROM users WHERE username='$username' AND email='$email' AND code='$code'"); while($row = mysql_fetch_array($getdata)) { $got_username=$row['username']; $got_email=$row['email']; $got_ref=$row['code']; $got_pass=$row['password']; } $newpassword = md5($newpasswordnomd); $repassword = md5($repasswordnomd); if($password==$got_pass) { if ($email==$got_email) { if ($username==$got_username) { if($newpassword==$repassword) { $resetpass=mysql_query("UPDATE users SET password='$repassword' WHERE email=='$email' AND username=='$username'"); echo "Your Password has been reset"; } else {echo "Your New Password and Repeat Password do not match";} } else {echo "Your Username does not match our records";} } else {echo "Your Email does not match our records";} } } ?> <form action='' method='POST' enctype='multipart/form-data'> <input type="hidden" name='code' value="<?php echo "$account_reference";?>"><p /> Email: <br/> <input type="email" name='email'><p /> Username: <br/> <input type='text' name='username'><p /> Password: <br/> <input type='text' name='password'><p /> New Password: <br/> <input type='text' name='newpassword'><p /> Repeat New Password: <br/> <input type='text' name='repassword'><p /> <input type='submit' name='resetpassword' value='Update'> Similar TutorialsHi guys I have this code, where it gets clicked from an email and then compares the tmp password etc and updates the new password in md5 format. I have been trying to find the issue why it doesnt update the password but i couldn't can u help me to find out why? Please note all the db field names are correct in the code below. thanks in advance <?php include ("include/global.php"); include ("include/function.php"); $code = $_GET['code']; if (!$code){ Header("Location: forgotpassword.php"); } else { if (isset($_POST['reset']) && $_POST['reset']) { $myemail=$row['email']; $mycurrentpass=$row['currentpass']; $mynewpass=$row['newpassword']; $myrepass=$row['repassword']; // $getcurrentinfo=mysql_query("SELECT email,password FROM users WHERE email='$myemail'"); while($row = mysql_fetch_array($getcurrentinfo)) { $currentemail=$row['email']; $currentpass=$row['password']; } // $newpassword = md5($mynewpass); $repeatpassword = md5($myrepass); if($myemail==$currentemail&& $currentpass==$mycurrentpass) { if($newpassword==$repeatpassword) { $updatepass=mysql_query("UPDATE users SET password='$newpassword' WHERE email='$myemail'"); } else {echo "Information provided are not correct, please try again with correct information";} } else {echo "Information provided are not correct, please try again with correct information";} } } ?> <html> <head> <script type="text/javascript" src="/js/jquery.js"></script> <script type="text/javascript" src="/js/jquery.validate.js"></script> <script type="text/javascript" src="/js/jquery.pstrength-min.1.2.js"></script> <script type="text/javascript"> $(function() { $('.password').pstrength(); }); $(document).ready(function(){ $("#form").validate({ rules: { email: { required: true, email: true } } }); }); </script> </head> <body> <fieldset> <form action='' method='POST' id='form'> <p>Enter Your Email: </p> <p> <input type='text' name='email' class="required"></td> <p>Enter Your Temporary Password: </p> <p> <input type='text' name='currentpass' class="required"></td> <p>Enter Your New Password: </p> <p> <input type='text' name='newpassword' class="password"></td> <p>Repeat Your New Password: </p> <p> <input type='text' name='repassword' class="required"></td> </table> </p> <p> <input type='submit' name='reset' value='Submit' id='form'> </form> </fieldset> </body> </html> This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=353345.0 i need help trying to get this delete feature to work its not deleting from the database (by the way i took out my database names and passwords at the top of the file) is it possible someone could help me, ive been working on this for like a week and cant figure out the problem. thanks! you can email me at spr_spng@yahoo.com picture 2.png is showing what it looks like Code: [Select] <?php $host="localhost"; // Host name $username="username"; // Mysql username $password="password"; // Mysql password $db_name="database_name"; // Database name $tbl_name="table_name"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <style> /*table affects look of the whole table look */ table { margin-left: auto; margin-right: auto; border: 1px solid #330000; border-collapse:collapse; width:70%; border-width: 5px 5px 5px 5px; border-spacing: 1px; border-style: outset outset outset outset; border-color: #330000 #330000 #330000 #330000; border-collapse: separate; background-color: #330000; #800517 f535aa #330000 school color #9A0000 school color2 #991B1E school color3 #CCCC99 school color4 #9A0000 } /*th is table header */ th { text-align: left; height: 2.5em; background-color: #330000; color: #FC0; font-size:1.5em; } /*td is table data or the cells below the header*/ td { text-align: left; height:1.0em; font-size:1.0em; vertical-align:bottom; padding:10px; border-width: 5px 5px 5px 5px; padding: 8px 8px 8px 8px; border-style: outset outset outset outset; border-color: #9A0000 #9A0000 #9A0000 #9A0000; background-color: #CCCC99; -moz-border-radius: 0px 0px 0px 0px; } </style> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td><form name="form1" method="post" action=""> <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td bgcolor="#FFFFFF"> </td> <td colspan="4" bgcolor="#FFFFFF"><strong>Pick Which Rows you want to delete, Then press delete.</strong> </td> </tr> <tr> <td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td> <td align="center" bgcolor="#FFFFFF">delete</td></tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['name']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['lastname']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td> <td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td> </tr> <?php } ?> <tr> <td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <? // Check if delete button active, start this // edited if($delete){ for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "DELETE FROM $tbl_name WHERE id='$del_id'"; $result = mysql_query($sql); } // if successful redirect to delete_multiple.php if($result){ echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">"; } } mysql_close(); ?> </table> </form> </td> </tr> </table> What would be a good way to reset a password ?
I was thinking
1 user requests reset password page or after faulty login suggest reset password page
2 fill in email address
3 check if email address exists
4 if address exist insert a random key into database
5 create a password reset url with random key and send to registered email address
6 after user clicks url in mail use $_GET to retrieve random key from password reset url
7 check if url exists in database
8 let user choose new password
9 check that password strenght is valid
10 encrypt password
11 write password in db
12 confirm page that password has been changed
Are there any obvious mistakes in this logic ?
This application will be aimed at 70-80 years old people so it has to be as easy to use as possible.
security questions and captcha's will be not really possible I am afraid.
thank you very much
anatak
Edited by anatak, 07 June 2014 - 08:08 PM. I've used this update statement before, even with parameter binding, something easy is off...
I'm trying to update a hash knowing a person's user name and email combination, this is not ideal I realize or safe. I actually generate a unique random hash per person who registers, I tell them to remember this eg. keep the email.
I don't know why the update statement is being bypassed.
So they enter username, email associated with username, new password. New password is hashed, replaces old one, redirect.
I've been echoing stuff just to see the flow of the code, what is being executed and what isn't.
if(empty($errors)){ $userrname = test_input($_POST['userrname']); $email = test_input($_POST['email']); $newpassword = test_input($_POST['newpassword']); $hash = password_hash($newpassword, PASSWORD_BCRYPT, array("cost" => 9)); $stmt = $link->prepare("SELECT username,hash FROM User where username=? And email=?"); $stmt->bind_param("ss",$userrname,$email); if($stmt->execute()) { $stmt->bind_result($username_from_db,$hash_from_db); if($stmt->fetch()){ $_SESSION['user']=$username_from_db; $query = "UPDATE User SET hash=$hash WHERE email=$email And username=$username_from_db"; if($result=$link->query($query)){ $_SESSION['status_message'] = "Password has been reset"; } }else { echo "no good"; } $host = $_SERVER['HTTP_HOST']; $uri = $_SERVER['REQUEST_URI']; // the path/file?query string of the page header("Location: newlocation.com"); exit; $link->close(); } Edited by moose-en-a-gant, 02 February 2015 - 12:48 AM. This works up until if (email == email2){ What is wrong? Is it a problem with the queries? if(isset($_SESSION['rest']) || isset($_SESSION['chef'])){ header('Location:index.php');} if (isset($_POST['submit'])) { $errors = array(); // VALIDATION SCRIPT HERE $newpass = generatepassword(); $link = mysql_connect("****","*****","******") or die ("Could not connect!"); mysql_select_db("****"); $query = "SELECT `username`, `type` FROM `users` WHERE `username`='$username'"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) {$type = $row['type'];} $numrows = mysql_num_rows($result); if ($numrows!=1){ $errors[] = 'Username not Found (Usernames are case sensitive)';} if($email == '' || $username == ''){ $errors[] = 'Please Fill in all Fields';} if (empty($errors)){ if ($type = 1){ $res1 = mysql_query("SELECT `username`,`email` FROM `rests` WHERE `username`='$username'"); while($row1 = mysql_fetch_array($res1)) {$email2 = $row1['email'];} }else{ $res2 = mysql_query("SELECT `username`,`email` FROM `chefs` WHERE `username`='$username'"); while($row2 = mysql_fetch_array($res2)) {$email2 = $row2['email'];} if ($email2 == $email) { echo $newpass; mysql_query("UPDATE `users` SET `password` = '$newpass' WHERE `username`='$username'"); //SEND EMAIL $my_email = 'enquiries@bakerdesigns.co.uk'; $email_from = 'Chef Match'; $email_subject = "Your New Password :: Chef Match"; $message = "Your new password is $newpass<br>You may change this via your control panel later."; $referer = $_SERVER['HTTP_REFERER']; $this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]; if ($referer != $this_url) { echo "You do not have permission to use this script from another URL."; exit; } $from = "From: $email2\r\n"; mail($email2, $email_subject, $message, $from); $thanks = 'An email has been sent to $email2 containing your new password. Please check your junk folder.'; }} }else{$errors[] = 'Email did not match Username'; $thanks = 'Email could not be sent.';} } Hi, I have a php password reset script that is not updating the database, or there is some other reason the new password reset is giving me a "wrong password" error on trying to use it. Any help Greatly appreciated! Thank you. Code: [Select] <?php define('IN_SCRIPT', true); // Start a session session_start(); ini_set ("display_errors", "1"); error_reporting(E_ALL); $host = " "; $database = " "; $username = " ; $password = " "; $tbl_name = " "; $conn = mysql_connect($host, $username, $password) or die("Could not connect: " . mysql_error()); if($conn) { mysql_select_db($database); echo "connected to database!!"; } else { echo "failed to select database"; } //this function will display error messages in alert boxes, used for login forms so if a field is invalid it will still keep the info //use error('foobar'); function error($msg) { ?> <html> <head> <script language="JavaScript"> <!-- alert("<?=$msg?>"); history.back(); //--> </script> </head> <body> </body> </html> <? exit; } //This functions checks and makes sure the email address that is being added to database is valid in format. function check_email_address($email) { // First, we check that there's one @ symbol, and that the lengths are right if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { // Email invalid because wrong number of characters in one section, or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode("@", $email); $local_array = explode(".", $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) { return false; } } } return true; } if (isset($_POST['submit'])) { if ($_POST['forgotpassword']=='') { error('Please Fill in Email.'); } if(get_magic_quotes_gpc()) { $forgotpassword = htmlspecialchars(stripslashes($_POST['forgotpassword'])); } else { $forgotpassword = htmlspecialchars($_POST['forgotpassword']); } //Make sure it's a valid email address, last thing we want is some sort of exploit! if (!check_email_address($_POST['forgotpassword'])) { error('Email Not Valid - Must be in format of name@domain.tld'); } // Lets see if the email exists $sql = "SELECT COUNT(*) FROM users WHERE email = '$forgotpassword'"; $result = mysql_query($sql)or die('Could not find member: ' . mysql_error()); if (!mysql_result($result,0,0)>0) { error('Email Not Found!'); } //Generate a RANDOM MD5 Hash for a password $random_password=md5(uniqid(rand())); //Take the first 8 digits and use them as the password we intend to email the user $emailpassword=substr($random_password, 0, 8); //Encrypt $emailpassword in MD5 format for the database $newpassword = md5($emailpassword); // Make a safe query $query = sprintf("UPDATE `users` SET `password` = '%s' WHERE `email` = '$forgotpassword'", mysql_real_escape_string($newpassword)); mysql_query($query)or die('Could not update members: ' . mysql_error()); //Email out the infromation $site_name = "MYSITECOM"; $site_email = "noreply@MYSITE.COM"; $subject = "Your New Password"; $message = "Your new password is as follows: ---------------------------- Password: $emailpassword ---------------------------- Please make note this information has been encrypted into our database This email was automatically generated."; if(!mail($forgotpassword, $subject, $message, "FROM: $site_name <$site_email>")){ die ("Sending Email Failed, Please Contact Site Admin! ($site_email)"); }else{ error('New Password Sent!.'); } } else { ?> <form name="forgotpasswordform" action="" method="post"> <table border="0" cellspacing="0" cellpadding="3" width="100%"> <caption> <div>Forgot Password</div> </caption> <tr> <td>Email Address:</td> <td><input name="forgotpassword" type="text" value="" id="forgotpassword" /></td> </tr> <tr> <td colspan="2" class="footer"><input type="submit" name="submit" value="Submit" class="mainoption" /></td> </tr> </table> </form> <? } ?> for some reason the password reset part of my site has stopped working and I am very sure that nothing has been altered in the related files since they was created. a visitor clicks 'reset password' link on our site and is taken to the following file which initiates the reset password routine. the visitor would get a link they need to click for the password to be altered and emailed to them. this first file does update the database with a `changeofpasswordcode`and this is emailed as it should be. Code: [Select] <?PHP include('includes/connection.php'); include('includes/functions.php'); date_default_timezone_set('Europe/London'); if(isset($_POST['reset']) && trim($_POST['reset']) == 'Reset Password') { $email = mysql_real_escape_string($_POST['email']); $checkConfirmed = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND verifyCode != '' LIMIT 1"); $checkEmail = mysql_query("SELECT account_id FROM customers WHERE email='$email' LIMIT 1"); $checkVerify = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND verified='No' LIMIT 1"); $checkBanned = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND suspended='Yes' LIMIT 1"); if(!$email) { $thisError = 'Please enter your e-mail address.'; } else if(! mysql_num_rows($checkEmail)) { $thisError = 'That email address is not registered with us.'; } else if(mysql_num_rows($checkConfirmed)) { $thisError = 'Your email address has not been verified, please check your email and following instructions within.'; } else if(mysql_num_rows($checkVerify)) { $thisError = 'Your account has not been approved by an Admin.'; } else if(mysql_num_rows($checkBanned)) { $thisError = 'Your account has been suspended by an Admin.'; } else { // } } include('includes/header.php'); ?> <body> <div class="headerBar"> <? include('includes/navigation.php');?> </div> <? headerText(); ?> <div class="content"> <div class="widthLimiter contentStyle"> <div class="formWrapper" style="width: 500px;"> <? if(isset($thisError)) { echo '<div class="errorDiv">',$thisError,'</div>'; } ?> <? if(isset($thisSuccess)) { echo '<div class="successDiv">',$thisSuccess,'</div>'; } ?> <span class="subHeader">Initiate Password Reset</span> <? // password reset $useremail = isset($_POST['email']) != '' ? trim($_POST['email']) : '' ; if ($useremail != "") { // get email and password and email them $sql = "SELECT * FROM `customers` WHERE (`email` = '" . mysql_real_escape_string($useremail) . "') LIMIT 1"; $res = mysql_query($sql); $email = @mysql_result($res, 0 ,'email'); $customerName = @mysql_result($res, 0 ,'fullname'); if(@mysql_num_rows($res) && @mysql_result($res, 0 ,'verified') == "Yes" && @mysql_result($res, 0 ,'suspended') == "No") { if(@mysql_result($res, 0 ,'changeofpasswordcode') != "") { $randomcode = @mysql_result($res, 0 ,'changeofpasswordcode'); } else { $randomcode = CreatePasswordResetCode(); } $_SESSION['customerName'] = $customerName; $_SESSION['customerEmail'] = $email; $_SESSION['randomcode'] = $randomcode; createEmailSend('passwordReset', 'Request to reset your password', 'customer'); $format = 'Y-m-d H:i:s'; $date = date( $format ); // set value in DB that email WAS sent $sql = "UPDATE `customers` SET `changeofpasswordcode` = '" . $randomcode . "', `newpasswordrequestedon` = '" . $date . "' WHERE `email` = '" . mysql_real_escape_string($email) . "' LIMIT 1"; $res = mysql_query($sql); ?><br /><br /><div>You will shortly receive an email which contains a reset password link,<br>please check your email and click this link to reset your password.<br /><br />A new password will then be emailed to you.</div><? } else { // not valid username entered. ?><br /><br /><div>If you are having trouble accessing your account please let us know<br />via <a href="mailto:admin@tm2cars.co.uk">email</a> and we shall look into this for you A.S.A.P.</div><? } } else { ?><br /><br /><div style=""><form method="post" action="">Please enter your Email Address for your account in the<br>field below and click 'Reset' to initiate a password reset.<br /><br /><input name="email" type="text" size="25"><input type="submit" name="reset" value=" Reset Password"></form></div> <? } ?> </div> </div> </div> <? include('includes/footer.php');?> </body> </html> once they get their email they click the link which taken them to the next page which would perform the change of password and have it emailed to them. the link has the correct `changeofpasswordcode` which is in the database but when the link is clicked the page says that the code is not valid as it is not in the DB. and then it removes the `changeofpasswordcode` it should only remove the `changeofpasswordcode` once the new password is setup and emailed, so that the link can not be used again. what i do not understand is why the second file does this, can anyone see what i might be doing wrong ? or what could be causing this ? Code: [Select] <?PHP include('includes/connection.php'); include('includes/functions.php'); date_default_timezone_set('Europe/London'); if(isset($_POST['reset']) && trim($_POST['reset']) == 'Reset') { $email = mysql_real_escape_string($_POST['email']); $checkVerify = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND verified='No' LIMIT 1"); $checkBanned = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND suspended='Yes' LIMIT 1"); if(!$email) { $thisError = 'Please enter your e-mail address.'; } else if(!$password) { $thisError = 'Please enter your password.'; } else if(mysql_num_rows($checkVerify)) { $thisError = 'Your account has not been approved by an Admin.'; } else if(mysql_num_rows($checkBanned)) { $thisError = 'Your account has been suspended by an Admin.'; } else { $password = md5($password); $checkAccount = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND password='$password' LIMIT 1"); if(mysql_num_rows($checkAccount)) { $_SESSION['FM_user'] = $email; header('Location: members.php'); exit; } else { $thisError = 'Your e-mail address and/or password is incorrect.'; } } } include('includes/header.php'); ?> <body> <div class="headerBar"> <? include('includes/navigation.php');?> </div> <? headerText(); ?> <div class="content"> <div class="widthLimiter contentStyle"> <div class="formWrapper"> <? if(isset($thisError)) { echo '<div class="errorDiv">',$thisError,'</div>'; } ?> <? if(isset($thisSuccess)) { echo '<div class="successDiv">',$thisSuccess,'</div>'; } ?> <span class="subHeader">Initiate Password Reset</span> <? // include("sendmail2010.php"); $securitycode = stripstring($_GET[pwr]); if ($securitycode != "") { $sql = "SELECT * FROM `customers` WHERE `changeofpasswordcode` = '".mysql_real_escape_string($securitycode)."' LIMIT 1"; $res = mysql_query($sql); if (@mysql_num_rows($res) && $securitycode != "") { $customerName = @mysql_result($res, 0 ,'fullname'); $email = @mysql_result($res, 0 ,'email'); $yourpasswordtologin = CreateNewPassword(); $format = 'Y-m-d H:i:s'; $date = date( $format ); $sql = "UPDATE `customers` SET `password` = '" . md5(mysql_real_escape_string($yourpasswordtologin)) . "', `changeofpasswordcode` = '', `newpasswordrequestedon` = '' WHERE `changeofpasswordcode` = '" . mysql_real_escape_string($securitycode) . "' LIMIT 1"; $res = mysql_query($sql); $_SESSION['customerName'] = $customerName; $_SESSION['customerEmail'] = $email; $_SESSION['generatePass'] = $yourpasswordtologin; createEmailSend('newPassword', 'Your new password', 'customer'); ?><div style="margin: 30px;">Thank you for completing your password reset process.<br><br>An email with a randomly generated password has been sent to your email address, please check your email account for this email as you will need this password to access your <?=$_SESSION['siteName'];?> account.<br><br><strong><em>Please check your 'spam folder' in case our emails are showing up there.</em></strong><br><br>You may now <a href="<?=$_SESSION['webAddress'];?>">sign in</a> to your account.</div><? } else { ?><div style="margin: 20px;">Sorry the link you clicked is and old password reset link or is not valid, please delete the email.<br><br>If you were trying to reset your password, please click the<br>'Member Login' link on our site and then click the 'Reset Password' link.</div><? } } ?> </div> </div> </div> <? include('includes/footer.php');?> </body> </html> I have tried resetting the password on my old account and the email never arrives , nor do my notifications for posts.
Hello I've recently been made aware that I need to hash the token I use when allowing users to reset their password. I have a working solution but I'm hoping someone could let me know if this is an adequate way of doing it; 1. User enters their email, I check whether their actually a member and then... create a passcode (1) create a salt (2) hash them together to create a passcode_hash (3) insert the (2) and (3) into the database send an email to the user with a link using (1) and the userid in the address 2. When the link is followed... $_GET the userid and lookup the salt and passcode_hash for that id hash together the passcode in the URL with the salt, and compare that to passcode_hash if that is successfull then allow an update of the password (show the update form) 3. The password update form is sent along with two hidden fields (the passcode and userid from the URL) On the form processing script I perform the same check as on Step 2 to check the passcode and user id have not been messed with Update the password and delete the passcode Hopefully that makes sense... is that correct? Here is my code that compares the passcode with the passcode_hash.... // get the passcode and email from URL (I will sanitize these) $passcode = $_GET['passcode']; $member_id = $_GET['uid']; // find the salt associated with the userid $stmt = $db->prepare("SELECT passcode,salt FROM members_verify WHERE members_id = ?"); $stmt->bind_param('i',$member_id); $stmt->execute(); $stmt->bind_result($db_passcode,$salt); $stmt->fetch(); $stmt->close(); // Create salted password $passcode_hash = hash('sha512', $passcode . $salt); if($passcode_hash===$db_passcode){ $allowUpdate = 'yes'; }Any advice would be great Edited by paddyfields, 07 June 2014 - 08:18 AM. Forgot Your Password Not working at the customer end, how to solve this error? Reset Password Email not sending to the customer mail account. Edited June 13, 2019 by aveeva<?php if (isset($_POST['reset-submit'])) { $selector = $_POST['selector']; $validator = $_POST['validator']; $password = $_POST['password']; $password2 = $_POST['password2']; // probably better to check this earlier if (empty($password) || empty($password2)) { header("Location: ../create-new-password.php?newpassword=empty&selector=$selector&validator=$validator"); } elseif ($password !== $password2) { header("Location: ../create-new-password.php?newpassword=passwordsnotmatch"); } $currentDate = date("U"); require "dbh.inc.php"; $sql = "SELECT * FROM reset_password WHERE selector=? AND expires >= $currentDate"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error 1"; exit(); } else { mysqli_stmt_bind_param($stmt, 'ss', $selector, $currentDate); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$row = mysqli_fetch_assoc($result)) { echo 'You need to re-submit your reset request.'; exit(); } else { $tokenBin = hex2bin($validator); $tokenCheck = password_verify($tokenBin, $row['token']); if (!$tokenCheck) { echo 'You need to re-submit your reset request.'; exit(); } else { $email = $row['email']; $sql = "SELECT * FROM users WHERE email = $email"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error 2"; exit(); } else { mysqli_stmt_bind_param($stmt, 's', $email); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$row = mysqli_fetch_assoc($result)) { echo "SQL error 3"; exit(); } else { $sql = "UPDATE users SET password=? WHERE email=?"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error4 "; exit(); } else { $hashed_password = password_hash($password, PASSWORD_DEFAULT); mysqli_stmt_bind_param($stmt, 'ss', $hashed_password, $email); mysqli_stmt_execute($stmt); $sql = 'DELETE FROM reset_password WHERE email=?'; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo 'SQL error5'; exit(); } else { mysqli_stmt_bind_param($stmt, 's', $email); mysqli_stmt_execute($stmt); header("Location: ../signup.php?newpassword=updated"); } } } } } } } mysqli_stmt_close($stmt); mysqli_close($conn); header('Location: ../reset-password.php?reset=success'); } else { header('Location: ../index.php'); } I always get this errors:
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\php_login_system-master\includes\reset-password.inc.php on line 26
But i dont find the mistake in the Code. Can someone help me please Code: [Select] <?php include 'config.php'; //include 'dbc.php'; ?> <?php function filter($data) { // <--line 6 $data = trim(htmlentities(strip_tags($data))); if (get_magic_quotes_gpc()) $data = stripslashes($data); $data = mysql_real_escape_string($data); return $data; } ?> <?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"; } $email = $data['email']; //check if activ code and user is valid as precaution $rs_check = mysql_query("select id from users where email='$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(); } if(empty($err)) { $new_pass = GenPwd(); $pass_reset = MD5($new_pass); //$sha1_new = sha1($new); //set update sha1 of new password + salt $rs_activ = mysql_query("update users set pass='$pass_reset' WHERE email='$email'") or die(mysql_error()); $host = $_SERVER['HTTP_HOST']; $host_upper = strtoupper($host); //send email $message = "Here are your new password details ...\n User Email: $email \n Passwd: $new_pass \n Thank You Administrator $host_upper ______________________________________________________ THIS IS AN AUTOMATED RESPONSE. ***DO NOT RESPOND TO THIS EMAIL**** "; mail($email, "Reset Password", $message, "From: \"Member Registration\" <auto-reply@$host>\r\n" . "X-Mailer: PHP/" . phpversion()); $msg[] = "Your account password has been reset and a new password has been sent to your email address."; //$msg = urlencode(); //header("Location: forgot.php?msg=$msg"); //exit(); } } ?> <html> <head> <title>Forgot Password</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <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(){ $("#actForm").validate(); }); </script> <link href="styles.css" rel="stylesheet" type="text/css"> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main"> <tr> <td colspan="3"> </td> </tr> <tr> <td width="160" valign="top"><p> </p> <p> </p> <p> </p> <p> </p> <p> </p></td> <td width="732" valign="top"> <h3 class="titlehdr">Forgot Password</h3> <p> <?php /******************** ERROR MESSAGES************************************************* This code is to show error messages **************************************************************************/ if(!empty($err)) { echo "<div class=\"msg\">"; foreach ($err as $e) { echo "* $e <br>"; } echo "</div>"; } if(!empty($msg)) { echo "<div class=\"msg\">" . $msg[0] . "</div>"; } /******************************* END ********************************/ ?> </p> <p>If you have forgot the account password, you can <strong>reset password</strong> and a new password will be sent to your email address.</p> <form action="forgot.php" method="post" name="actForm" id="actForm" > <table width="65%" border="0" cellpadding="4" cellspacing="4" class="loginform"> <tr> <td colspan="2"> </td> </tr> <tr> <td width="36%">Your Email</td> <td width="64%"><input name="email" type="text" class="required email" id="txtboxn" size="25"></td> </tr> <tr> <td colspan="2"> <div align="center"> <p> <input name="doReset" type="submit" id="doLogin3" value="Reset"> </p> </div></td> </tr> </table> <div align="center"></div> <p align="center"> </p> </form> <p> </p> <p align="left"> </p></td> <td width="196" valign="top"> </td> </tr> <tr> <td colspan="3"> </td> </tr> </table> </body> </html> Fatal error: Cannot redeclare filter() (previously declared in/forgot.php:6) what is wrong ? Hello PhP Freaks forum In the past weeks ive been trying to make a website, where you can register. Everything seems to work except my cherished Change password feature. Everytime you try to change the password, it just resets it to nothing. Here is the code below. <?php if(isset($_SESSION['username'])) { $username = $_SESSION['username']; $lastname = $_SESSION['lastname']; $firstname = $_SESSION['firstname']; $email = $_SESSION['email']; echo " <h4>Options for:</h4> $username <br /> <br /> First name: $firstname <br />Last name: $lastname <br /><br /><h3>Want to change your password:</h3><br /> <form action='?do=option' method='post'> Old password <input type='password' placeholder='Has to be between 5-15 digits' name='password' size='30' value='' /><br /> <br /> New Password<input type='password' placeholder='Has to be between 5-15 digits' name='newpass' size='30' value='' /><br /> <br /> Confirm new password <input type='password' placeholder='Has to be between 5-15 digits' name='passconf' size='30' value='' /><br /> <center></div><input type='submit' value='Submit'/></center></form>"; }else{ echo 'Please login to view your options!'; } $password = $_REQUEST['password']; $pass_conf = $_REQUEST['newpass']; $email = $_REQUEST['passconf']; $connect = mysql_connect("Host", "User", "Password"); if(!$connect){ die(mysql_error()); } //Selecting database $select_db = mysql_select_db("My Database", $connect); if(!$select_db){ die(mysql_error()); } //Find if entered data is correct $result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'"); $row = mysql_fetch_array($result); $id = $row['id']; mysql_query("UPDATE users SET password='$newpass' WHERE username='$user'") ?> And i do know that i dont have a if(Empty($newpass)){ Die(Please fill out the new password) } Or any security on the others, but the problem just seems that it resets the password into nothing Hope i can get this fixed Best Regards William Pfaffe require_once 'includes/upload.class.php'; $upload = new uploads(); $details = $upload->getFileInformation($id); <?php echo $details['upload_desc']; ?> then here the class. require_once 'db.class.php'; class uploads extends database { private $uploadData; function uploadFile() { public function getFileInformation($id) { $this->uploadData = $this->readData("uploadfiles", "upload_id", $id); return $this->uploadData; } But it wont work! Ok, I am a complete noob when it comes to php. I am slowly learning it but I turned to youtube for a tutorial on a registration/login page. I found a good tutorial http://www.youtube.com/watch?v=ngqeWUIDlnk&feature=channel but for some reason my php is NOT working. I have it exactly the way he does but it wont echo anything or work at all. The login page worked great in his tutorial. What do I have wrong? I cant figure it out. Please help! echo "<h1>Register</h1>"; $submit = $_POST['submit']; $fullname = strip_tags($_POST['name']); $username = strip_tags($_POST['user']); $password = strip_tags($_POST['password']); $verifypassword = strip_tags($_POST['verifypassword']); $date = date("Y-m-d"); if ($submit) { if($fullname&&$username&&$password&&$verifypassword) { password = md5($password); verifypassword= = md5($verifypassword); } else echo "Please fill in all fields!"; } Code: [Select] <html> <form action='register.php' method='POST'> <table> <tr> <td>Full Name:</td> <td><input type='text' name='name'></td> </tr> <tr> <td>Username:</td> <td><input type='text' name='user'></td> </tr> <tr> <td>Password:</td> <td><input type='password' name='password'></td> </tr> <tr> <td>Verify Password:</td> <td><input type='password' name='verifypassword'></td> </tr> </table> <p><input type='submit' name='submit' value='Submit'></p> </form> </html> $last = mysql_query("SELECT MAX('id') FROM comments WHERE submittedby='$username'"); can any1 help me? For some reason this wont work.. Index is jsut returned blank ... Hmm Index.php : <?php include("http://www.website.com/cookie.php"); ?> Cookie.php: <?php if (isset($_COOKIE["background"])) $background = $_COOKIE['background']; else $background = " bgcolor='#FFFFFF'"; ?> It works perfectly if I just enter the code without using a include ... Hi guys, I have an update page where users can update their information, i have a different update page which works fine with almost the same code, but this one wont update anything. it does show the data but it wont update it, can u help please? <?php session_start(); include ("../../global.php"); //welcome messaage $username=$_SESSION['username']; echo "$username"; $query=mysql_query("SELECT id FROM users WHERE username='$username'"); while($row = mysql_fetch_assoc($query)) { $user_id = $row['id']; } $ref=$_GET['reference']; if (isset($_POST['register']) && $_POST['register']){ $title = addslashes(strip_tags($_POST['title'])); $update=mysql_query("UPDATE msg SET title ='$title' WHERE reference='$ref'"); } ?> <html> <head> </head> <body> <form action='edit-msgs.php' method='POST' enctype='multipart/form-data'> Title:<br /> <input type='text' name='title' id='title' value='<?php $getdata = "SELECT title FROM msg WHERE reference='$ref' AND referal_id='$user_id'"; $result = mysql_query($getdata); $row = mysql_fetch_assoc($result); echo $row['title'];?>'><p /> <input type='submit' name='register' value='Update'> </form> </body> </html> It works other then the fact it won't go to another page to see results. <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","username","password"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("database") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "select * from the_table where 1st_field like \"%$trimmed%\" order by 1st_field"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; echo "<p><a href=\"http://www.google.com/search?q=" . $trimmed . "\" target=\"_blank\" title=\"Look up " . $trimmed . " on Google\">Click here</a> to try the search on google</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> |