PHP - Magento 1.9.2.3 Customer Password Reset Not Working
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 aveevaSimilar TutorialsHi, 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> This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=353345.0 Observer not triggered and log file not created.
app/etc/modules/Gta_KolupadiRestrict.xml <?xml version="1.0" encoding="UTF-8"?> <config> <modules> <Gta_KolupadiRestrict> <active>true</active> <codepool>local</codepool> </Gta_KolupadiRestrict> </modules> </config>
app/code/local/Gta/KolupadiRestrict/etc/config.xml
<?xml version="1.0"?> <config> <modules> <Gta_KolupadiRestrict> <version>1.0.0</version> </Gta_KolupadiRestrict> </modules> <global> <models> <gta_kolupadirestrict> <class>Gta_KolupadiRestrict_Model</class> </gta_kolupadirestrict> </models> </global> <frontend> <events> <checkout_cart_product_add_after> <observers> <Gta_KolupadiRestrict_Model_Observer> <type>singleton</type> <class>Gta_KolupadiRestrict_Model_Observer</class> <method>cartevent</method> </Gta_KolupadiRestrict_Model_Observer> </observers> </checkout_cart_product_add_after> </events> </frontend> </config>
app/code/local/Gta/KolupadiRestrict/Model/Observer.php <?php // Mage::log('fine dude', null, 'logfile.log'); //create class class Gta_KolupadiRestrict_Model_Observer { //create function public function cartevent(Varien_Event_Observer $observer) {
$event = $observer->getEvent(); Mage::log($event->getName(),null,'event.log');
} } ?> Edited August 6, 2019 by aveevaThis 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.';} } 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. 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. Created module like No other products add to cart if restricted product available in cart and vice versa. My Module : app/etc/modules/Brst_Test.xml<?xml version="1.0"?> <config> <modules> <Brst_Test> <active>true</active> <codePool>community</codePool> </Brst_Test> </modules> </config> This is my observer file app/code/community/Brst/Test/Model/Observer.php<?php ini_set('display_errors', '1'); // Mage::log('Hy observer called', null, 'logfile.log'); class Brst_Test_Model_Observer { //Put any event as per your requirement public function logCartAdd() { $product = Mage::getModel('catalog/product') ->load(Mage::app()->getRequest()->getParam('product', 0)); $cart_qty = (int) Mage::getModel('checkout/cart')->getQuote()->getItemsQty(); if ($product->getId()==31588 && cart_qty > 0) { Mage::throwException("You can not add This special Product, empty cart before add it"); } // $quote = Mage::getSingleton('checkout/session')->getQuote(); // if ($quote->hasProductId(2)) //{ // Mage::getSingleton("core/session")->addError("Cart has Special Product you can not add another"); // return; // } $quote = Mage::getModel('checkout/cart')->getQuote(); foreach ($quote->getAllItems() as $item) { $productId = $item->getProductId(); if($productId==31588){ Mage::throwException("Cart has Special Product you can not add another"); } } } } ?> app/code/community/Brst/Test/etc/config.xml <?xml version="1.0"?> <config> <modules> <Brst_Test> <version>0.1.0</version> </Brst_Test> </modules> <global> <models> <brst_test> <class>Brst_Test_Model</class> </brst_test> </models> </global> <frontend> <events> <controller_action_predispatch_checkout_cart_add> <observers> <brst_test_log_cart_add> <class>brst_test/observer</class> <method>logCartAdd</method> </brst_test_log_cart_add> </observers> </controller_action_predispatch_checkout_cart_add> </events> </frontend> </config>
Not working, how to solve the error? Hi 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> 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. 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'> I have tried resetting the password on my old account and the email never arrives , nor do my notifications for posts.
<?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 ? here is my change password script (This is being done by the admin)
<?php error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', '1'); require 'connect.php'; if(isset($_POST['change'])) { $newp = trim($_POST['npass']); $confp = trim($_POST['cpass']); if(empty(trim($newp))) { echo "<h3><center>You did not enter a new password!</center></h3>"; exit(); } if(empty(trim($confp))) { echo "<h3><center>You must confirm the password!</center></h3>"; exit(); } if($confp !== $newp) { echo "Passwords do not match!, try again."; } else { $sql = "UPDATE $db_name SET cpass='$password' WHERE id=' ".$row['id']." '"; echo " ".$row['username']."\s password has been reset! "; } } ?> <html><title> Change password </title><head><style>#form {border-radius: 20px;font-family: sans-serif; margin-top: 60px; padding: 30px;background-color: #aaa;margin-left: auto; margin-right: auto; width: 500px; clear: both;} #form input {width: 100%; clear: both;} #form input:hover {border: 1px solid #ff0000;}</style></head> <body> <div id="form"> <form action='' method='POST'> <h2><b><center>Change Password</center></b></h2><br> <tr> <td><b>New password:</b><input type="password" name="npass" placeholder="Enter new password" /></td><br><br> <td><b>Confirm password:</b><input type="password" name="cpass" placeholder="Confirm password" /></td><br><br> <td><input type="submit" name="change" value="Change!" /></td> </tr> </form> </div><!-- end of form div --> </body> </html>I'm getting Notice: Undefined variable: row in C:\xampp\htdocs\Login\web_dir\changepassword.php on line 30 Notice: Undefined variable: row in C:\xampp\htdocs\Login\web_dir\changepassword.php on line 32And it say's \s password has been reset!It's saying that the variable row is undefined, it's defined in my edit user / select user page <?php error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', '1'); session_start(); require 'connect.php'; echo "<title> Edit a user </title>"; $sql = "SELECT id, username FROM $tbl_name ORDER BY username"; $result = $con->query($sql); while ($row = $result->fetch_assoc()) { echo "<div id='l'><tr><td>{$row['username']}</td> | <td><a href='editUser.php?id={$row['id']}'>Edit User</a> |</td> <td><a href='changepassword.php?id={$row['id']}'>Change Password</a> |</td> <td><a href='banUser.php?id={$row['id']}'>Ban User</a></td><br><br> </tr></div>\n"; } ?>Also it doesn't actually UPDATE the password. I paid someone to develop my site and for some reason the Forgot Password page is not working. Once the user types in their email address and submits, nothing happens. The user should get a message displayed instantly letting them know if the password was sent or if their account was not found. Any help would be greatly appreciated! Code: [Select] [php] <? include_once "connect.php"; if(isset($_SESSION['RES_LoginID']) && $_SESSION['RES_LoginID']!="") { echo "<script>window.location='myprofile.php';</script>"; exit; } // code to send mail to user (account details) if(isset($_REQUEST["btnLogin"])) { $sel="select name,email,password from users where email='".$_REQUEST['RES_EMAIL']."'"; $urs=mysql_query($sel); if (mysql_affected_rows()>0) // send mail if mail existing in database { $row=mysql_fetch_array($urs); $name=$row['name']; $username=$row['email']; $password=$row['password']; $message="<link href='".WEBSITEURL."site.css' rel='stylesheet' type='text/css' /> <body> <table border=0 cellspacing='5' cellpadding=0 width=600 align='center' class='purple_11'> <tr><td> $SITE_LOGO<br><br> Dear <b>".$name."</b>,<br><br> Your login details a <br> Username : $username<br> Password : $password<br> <br><br> Login at: <a href='".WEBSITEURL."login.php' target='_blank'>$SITE_NAME</a><br><br><br> Thank You,<br> $SITE_NAME </td></tr></table> </body>"; $sub="Forgot Password?"; SendHTMLMail($username,$sub,$message,ADMIN_MAIL); $redirect="<script>window.location='forgot_password.php?msgs=1';</script>"; } else // if mail doesnot match { $redirect="<script>window.location='forgot_password.php?msgs=2';</script>"; } echo $redirect; exit; } // generate message for display $msg=""; if(isset($_REQUEST['msgs'])) { switch($_REQUEST['msgs']) { case 1 : $msg="Your password sent successfully."; break; case 2 : $msg="Email Address does not exists."; break; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[url=http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd[/url]"> <html xmlns="[url=http://www.w3.org/1999/xhtml]http://www.w3.org/1999/xhtml[/url]"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="<?=$KEYWORD?>" /> <link rel="shortcut icon" href="images/favicon.gif"> <title><?=$SITE_TITLE?></title> <link href="site.css" rel="stylesheet" type="text/css" /> <script language="javascript"> function valid_login() { form=document.frmLogin; if(form.RES_EMAIL.value=="") { alert("Please enter your email.") form.RES_EMAIL.focus(); return false; } else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.RES_EMAIL.value))) { alert("Please enter a proper email address."); form.RES_EMAIL.focus(); return false; } else { form.submit(); } } </script> </head> <body onload="MM_preloadImages('images/about-us-hover.jpg','images/my-pofile-hover.jpg','images/help-hover.jpg','images/home.jpg')"> <table width="1000" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="1251" align="center" valign="top" class="main_bg"><table width="850" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="153" align="left" valign="top"><? include_once "top.php"; ?></td> </tr> <tr> <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height="18"></td> </tr> <tr> <td><table width="822" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="11" align="left" valign="top"><img src="images/white-crv1.jpg" width="11" height="11" /></td> <td width="100%" height="11" class="gray-top-bdr"><img src="images/blank-img.gif" width="1" height="1" /></td> <td width="11" align="right" valign="top"><img src="images/white-crv2.jpg" width="11" height="11" /></td> </tr> <tr> <td width="11" class="gray-left-bdr"><span class="gray-top-bdr"><img src="images/blank-img.gif" width="1" height="1" /></span></td> <td align="center"><? include("gad_hori.php");?></td> <td width="11"class="gray-rightt-bdr"><span class="gray-top-bdr"><img src="images/blank-img.gif" width="1" height="1" /></span></td> </tr> <tr> <td width="11" height="11" align="left" valign="bottom"><img src="images/white-crv3.jpg" width="11" height="11" /></td> <td height="11" class="gray-bot-bdr"><img src="images/blank-img.gif" width="1" height="1" /></td> <td width="11" height="11" align="left" valign="bottom"><img src="images/white-crv4.jpg" width="11" height="11" /></td> </tr> </table></td> </tr> <tr> <td height="73" align="left" valign="top"></td> </tr> <tr> <td align="left" valign="top"><table width="822" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="587" align="left" valign="top"><table width="587" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="19"><img src="images/gray-left-crv.jpg" width="19" height="247" /></td> <td width="321" align="left" valign="top" class="gry-bg-rpt"> <form name="frmLogin" id="frmLogin" action="" method="post"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height="20"></td> </tr> <tr> <td height="27" class="gray-bot-bdr red-txt20" valign="top">Forgot Password?</td> </tr> <tr> <td height="25" align="center" valign="middle" class="red-txt12"><?=$msg;?></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td colspan="2" height="22" align="left" style="padding-left:15px;"><strong>Please enter your E-mail address to get the password .</strong></td> </tr> <tr height="15"><td> </td></tr> <tr> <td width="33%" align="center"><strong>Email Address :</strong></td> <td width="67%"><input name="RES_EMAIL" type="text" class="input" style="width:176px; height:20px;"/></td> </tr> <tr> <td> </td> <td height="40" align="center"> <input type="submit" name="btnLogin" value="" class="btn_submit" title="Sign In" onclick="return valid_login();" /> </td> </tr> <tr> <td> </td> <td height="25" align="left" valign="bottom">Know your password? <a href="login.php">Login here</a></td> </tr> </table></td> </tr> </table> </form> </td> <td width="247" align="left" valign="top" class="red-box2"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height="88"> </td> <td> </td> </tr> <tr> <td width="77"> </td> <td><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height="85" align="left" valign="top"><img src="images/dont-acc.jpg" width="135" height="65" hspace="10" /></td> </tr> <tr> <td height="40" align="left" valign="top"><a href="register.php"><img src="images/register-but.jpg" alt="Register Here" width="146" height="30" border="0" /></a></td> </tr> </table></td> </tr> </table></td> </tr> </table></td> <td width="235" align="right" valign="top"><? include("square_ads.php");?></td> </tr> </table></td> </tr> </table></td> </tr> <tr> <td valign="top"><? include_once "bottom.php"; ?></td> </tr> </table></td> </tr> </table> </body> </html>[/php] I've somehow lost the password for my account, but when I use the forget password link, it says that it sent a reset link, yet I never get it.
Additionally, when I registered this temporary account to report the problem, I didn't receive a confirmation email for that either.
This is my registering script: <?php include('connectvars.php'); $user_email = strip_tags(trim($_POST['email'])); $firstname = strip_tags(trim($_POST['firstname'])); $lastname = strip_tags(trim($_POST['lastname'])); $nickname = strip_tags(trim($_POST['nickname'])); $password = strip_tags($_POST['password']); $repassword = strip_tags($_POST['repassword']); $dob = $_POST['dob']; $find_us_question = strip_tags(trim($_POST['find_us_question'])); if (isset($_POST['submit_signup'])) { if ((empty($user_email)) || (empty($firstname)) || (empty($lastname)) || (empty($nickname)) || (empty($password)) || (empty($dob))) { echo "Please fill out all the fields!"; } else { // check char length of input data if (($nickname > 30) || ($firstname > 30) || ($lastname > 30) || ($user_email > 50)) { echo "Your nickname, first- and/or lastname seem to be too long, please make sure you have them below the maximum allowed length of 30 characters!"; } else { // check password char length if (($password > 25) || ($password < 6)) { echo "Your password must be between 6 and 25 characters!"; } else { // encrypt password $password = sha1($password); $repassword = sha1($repassword); if ($password != $repassword) { echo "Please make sure your passwords are matching!"; } else { $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query = sprintf("INSERT INTO user (firstname, lastname, nickname, password, email, dob, doj) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', now())", mysqli_real_escape_string($dbc, $firstname), mysqli_real_escape_string($dbc, $lastname), mysqli_real_escape_string($dbc, $nickname), mysqli_real_escape_string($dbc, $password), mysqli_real_escape_string($dbc, $user_email), $dob); mysqli_query($dbc, $query); mysqli_close($dbc); echo "You have been successfully registered!"; } } } } } ?> A bunch of nested if statements, the read-ability gets worse after a while, I'm new to programming so I don't know if there's a better more read-able solution. Anyway, every time I try to sign up it's printing out the echo message: "Your password must be between 6 and 25 characters!" Which derives from: // check password char length if (($password > 25) || ($password < 6)) { echo "Your password must be between 6 and 25 characters!"; } else { EVEN if I stay between 6 and 25 characters it's still printing out this error message, let's say I have a password of 8 characters, and I've entered everything else correctly, it's still giving me all the time this error message, and I can not figure out why. I have a problem w/ a widely used password protect php code. I use a business directory program that allows custom input fields. I'm using this code to password protect a business listing page in my directory code. I created custom fields for the username & password so a listing can enter their own user/pass but when I test it it won't work when I'm calling/echoing the fields. When I hardcode it w/ a user/pass it works. Any ideas on how I should recode this?: Quote <?php // Define your username and password $username = "<?php echo $custom_74; ?>"; $password = "<?php echo $custom_16; ?>"; if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) { ?> <h1>Login</h1> <form name="form" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> <p><label for="txtUsername">Username:</label> <br /><input type="text" title="Enter your Username" name="txtUsername" /></p> <p><label for="txtpassword">Password:</label> <br /><input type="password" title="Enter your password" name="txtPassword" /></p> <p><input type="submit" name="Submit" value="Login" /></p> </form> <?php } else { ?> I close the code correctly. <?php echo $custom_74; ?> & <?php echo $custom_16; ?> are just incidently my custom field echo codes. I have over 150 custom fields working fine for user/listee options. The password protect code won't accept echos it seems as coded above. Thanks, Gene I have one restricted product, here how to do selected single product should be purchased alone? No other products are eligible to add add-to-cart if this product available in the add-to-cart, same if other products available in add-to-cart this product not eligible to add add-to-cart. How to achieve this in Magento? |