Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Oct 2009
    Posts
    445
    Thanks
    7
    Thanked 3 Times in 3 Posts

    can anyone see where i might be going wrong with my (reset password) code

    I have been having a lot of problems with my code which did work once but now it does not, as far as I know the code has not been changed for months and has worked with no problem until now.

    The reset password is in two parts.
    (startresetpw.php)
    1.1) Enter email address of the user account and submit.
    1.2) A check is done to see if a hashcode exists in the USER database, if it does grab that hashcode, if not create a random hashcode and stored in the database for that user.
    1.3) An email is sent to the users email with a link to be clicked that has the unique random hashcode in it.
    1.4) Display message that email with link was sent.

    User gets email and clicks the link.

    (resetpw.php)
    2.1) The hashcode in the URL (?pwr=abcdefg) is checked to see if it exists in the database
    2.2) If it does then a new password (letters only) is created and store in the database and the hashcode is removed from the database to prevent it being used again, if it does not exist then a message is displayed to say that it is not valid.

    2.3) An email with the new password is sent to the users email.

    this is the sort of method my script should be taking, but for some reason it seems to display that the hashcode is not valid and yet still remove it as though it was valid !

    The resetpw.php file is actually doing things that it should not be doing.

    take the following..


    if (checkSomething) { do this; do somethingElse; } else { do somethingMore; }

    if the checkSomething is true then it does the first part (do this; do somethingElse) else it does (do somethingMore)

    thats what should happen, but for some reason my code is doing this..

    if does the first part to find out if the statement is true or not then does this if it is true...

    (do this; do somethingMore)

    as you can see this should not be possible, but it is actually what happens with this code in resetpw.php !

    can anyone see why this would be happening ? I have had this script checked on three different servers of my friends and all of them are doing the same thing.

    here are the scripts

    connection.php
    Code:
    <?
      $dbhost = 'localhost';
      $dbuser = 'site_user';
      $dbpass = 'mypassword';
      $dbname = 'site_dbname';
    
      $connect = @mysql_connect($dbhost,$dbuser,$dbpass);
      
      @mysql_select_db("$dbname",$connect);
      @mysql_query("SET NAMES 'utf8'");
    ?>


    startresetpw.php
    Code:
    <?PHP
      include('includes/connection.php');
      include('includes/functions2.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 {
          //
        }
      }
    
    
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="en">
    <head>
    <title>..</title>
    </head>
    <body>
    
    
      <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');
    ?><br><br>Line 61 of startresetpw.php would just basically send an email with this link...<br>
    ignor the fact that the link seems to split up on two lines this is only due to the sites display, the link is on one line in the email.
    <br>
    <br>
    http://www.site.com/resetpw.php?pwr=<? echo($_SESSION['randomcode']); ?>
    <br><br>
    <?
    
    
    
    
    		$format = 'Y-m-d H:i:s'; $date = date( $format );
    		// set value in DB that email WAS sent
    											$sql = "UPDATE `customers` SET `changeofpasswordcode` = '" . mysql_real_escape_string($randomcode) . "', `newpasswordrequestedon` = '" . $date . "' WHERE `email` = '" . mysql_real_escape_string($email) . "' LIMIT 1";
    											$res = mysql_query($sql);
    //echo("67:<br>".$sql."<br>");
    		?><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.
    //echo("70:<br>".$sql."<br>");
    				?><br /><br /><div>If you are having trouble accessing your account please let us know<br />via <a href="">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>
    
    </body>
    </html>

    resetpw.php
    Code:
    <?PHP
    define('IN_SCRIPT', true);
    // Start a session
    session_start();
      
    include('includes/connection.php');
      include('includes/functions2.php');
      date_default_timezone_set('Europe/London');
    
    
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="en">
    <head>
    <title>..</title>
    </head>
    <body>
    
      <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);
    
    //echo("<br><br><br>:");
    //print_r(mysql_num_rows($res));
    //echo(":<br><br><br>");
    //echo("69:<br>");
    		if (@mysql_num_rows($res)) {
    //echo("71:<br>");
    		$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)) . "', `password2` = '" . mysql_real_escape_string($yourpasswordtologin) . "', `changeofpasswordcode` = '', `newpasswordrequestedon` = '' WHERE `changeofpasswordcode` = '" . mysql_real_escape_string($securitycode) . "' LIMIT 1";
    //echo("77:<br>".$sql."<br>:");
    		$res = mysql_query($sql);
    //print_r($res);
    //echo("79:<br>");
    		$_SESSION['customerName'] = $customerName;
    		$_SESSION['customerEmail'] = $email;
    		$_SESSION['generatePass'] = $yourpasswordtologin;
    		createEmailSend('newPassword', 'Your new password', 'customer');
    //echo("send");
    		?><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></div><?
    //echo("68:<br>");
    		} else {
    //echo("88:<br>");
    		?><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><?
    //echo("90:<br>");
    		}
    //echo("92:<br>");
    }
    //echo("94:<br>");
    ?>
          </div>
        </div>
      </div>
    
    </body>
    </html>



    functions.php
    Code:
    <?
    
    function stripstring($textstring) {
    	$textstring = trim($textstring);
    	$strPattern = "/[^a-zA-Z0-9\r\n,. ]/";
    	$textstring = preg_replace($strPattern, "", $textstring); // remove all but letter and numbers
    	$textstring = preg_replace("/ {2,}/", " ", $textstring); // replace double spaces with single
    	$textstring = preg_replace("/ \r\n/", "\r\n", $textstring); // remove single space 'windows' return
    	$textstring = preg_replace("/(\r\n){2,}/", "\r\n", $textstring); // remove 'windows' double returns
    	$textstring = preg_replace("/ \r/", "\r", $textstring); // remove single space 'mac' return
    	$textstring = preg_replace("/\r{2,}/", "\r", $textstring); // remove 'mac' double returns
    	$textstring = preg_replace("/ \n/", "\n", $textstring); // remove single space 'unix' return
    	$textstring = preg_replace("/\n{2,}/", "\n", $textstring); // remove 'unix' double returns
    	$textstring = preg_replace("/\r\n /", "\r\n", $textstring); // remove 'windows' return single space 'windows' return
    	$textstring = preg_replace("/\r /", "\r", $textstring); // remove 'mac' return single space 'mac' return
    	$textstring = preg_replace("/\n /", "\n", $textstring); // remove 'unix' return single space 'unix' return
    	return ($textstring);
    	}
    
    function CreateNewPassword() {
    	// setup random password	//$acceptedChars = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789';
    	$acceptedChars = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN';
    	$max = strlen($acceptedChars)-1;
    	$yourpasswordtologin = ""; $letters = rand(5, 8);
    		for($i=0; $i < $letters; $i++) { $yourpasswordtologin .= $acceptedChars{mt_rand(0, $max)}; }
    	return $yourpasswordtologin;
    	}
    
    function CreatePasswordResetCode() {
    	// /*
    	// set new $record_ref.
    	$ResetCode =  md5(rand(10, rand(10, 1000000000)));
    	// check if exisits in DB.
    	$sql = "SELECT * FROM `customers` WHERE `changeofpasswordcode` = '". $ResetCode ."'";
    	$get_records_with_reset_code = mysql_query($sql);
    	// count entries in DB for $record_ref.
    	$count_records =  mysql_num_rows($get_records_with_reset_code);
    
    		while ($count_records > 0) {
    		// set new $record_ref.
    		$ResetCode =  (rand(10, rand(10, 1000000000)));
    		// check if exisits in DB.
    		$sql = "SELECT * FROM `customers` WHERE `changeofpasswordcode` = '". $ResetCode ."'";
    		$get_records_with_reset_code = mysql_query($sql);
    		// count entries in DB for $record_ref.
    		$count_records =  mysql_num_rows($get_records_with_reset_code);
    		}
    	// */
    	return $ResetCode;
    	}
    
    
    
    function CreateVerifyCode() {
    	// /*
    	// set new $record_ref.
    	$verifyCode =  md5(rand(10, rand(10, 1000000000)));
    	// check if exisits in DB.
    	$sql = "SELECT * FROM `customers` WHERE `verifyCode` = '". $verifyCode ."'";
    	$get_records_with_verify_code = mysql_query($sql);
    	// count entries in DB for $record_ref.
    	$count_records =  mysql_num_rows($get_records_with_verify_code);
    
    		while ($count_records > 0) {
    		// set new $record_ref.
    		$verifyCode =  (rand(10, rand(10, 1000000000)));
    		// check if exisits in DB.
    		$sql = "SELECT * FROM `customers` WHERE `verifyCode` = '". $verifyCode ."'";
    		$get_records_with_verify_code = mysql_query($sql);
    		// count entries in DB for $record_ref.
    		$count_records =  mysql_num_rows($get_records_with_verify_code);
    		}
    	// */
    	return $verifyCode;
    	}
    
    ?>


    a sample of the database (change the email address my@email.com below to your own if you are testing this on your own servers)
    Code:
    CREATE TABLE IF NOT EXISTS `customers` (
      `account_id` smallint(15) NOT NULL auto_increment,
      `account_type` varchar(8) NOT NULL default 'customer',
      `ip_address` varchar(15) NOT NULL default '0.0.0.0',
      `banned` char(3) NOT NULL default 'No',
      `company` varchar(100) NOT NULL,
      `fullname` char(100) NOT NULL,
      `email` varchar(150) NOT NULL,
      `mobile` varchar(20) NOT NULL,
      `password` varchar(50) NOT NULL,
      `password2` varchar(50) NOT NULL,
      `lastlogindatetime` datetime NOT NULL default '0000-00-00 00:00:00',
      `lastlogindatetimeFailed` datetime NOT NULL default '0000-00-00 00:00:00',
      `time_created` smallint(15) NOT NULL,
      `verified` varchar(3) NOT NULL default 'No',
      `suspended` varchar(3) NOT NULL default 'No',
      `changeofpasswordcode` varchar(32) NOT NULL,
      `newpasswordrequestedon` datetime NOT NULL default '0000-00-00 00:00:00',
      `verifyCode` varchar(32) NOT NULL,
      PRIMARY KEY  (`account_id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=140 ;
    
    --
    -- Dumping data for table `customers`
    --
    
    INSERT INTO `customers` (`account_id`, `account_type`, `ip_address`, `banned`, `company`, `fullname`, `email`, `mobile`, `password`, `password2`, `lastlogindatetime`, `lastlogindatetimeFailed`, `time_created`, `verified`, `suspended`, `changeofpasswordcode`, `newpasswordrequestedon`, `verifyCode`) VALUES
    (127, 'customer', '', 'No', 'MY COMPANY', 'My Full Name', 'my@email.com', '', '4d9f95422da3599de9b846a652667419', 'vALygyni', '2011-09-13 10:58:18', '0000-00-00 00:00:00', 32767, 'Yes', 'No', '', '', '');

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    This is far too much code for me to go through in the morning.
    The first thing you mention is that this has worked, and hasn't been a problem until now. This indicates that either:
    1. The code has changed.
    2. The environment has changed
    3. The client has changed


    My money would go against 3 and then 2. The first thing to check is the HTML source code to make sure that it doesn't show any html tags that are actually PHP ones. This is because you are using short_tags which is not a mandatory directive in PHP.
    Next, take the link OUT of the email, and paste it directly into the url. See if that works. That will only apply if there is actually a hash to work with, and one that matches the inserted one. If it does AND it works, you know the problem is the browser and / or the email client itself. If it does AND it does not work AND the hash does match the database, you know the problem is in resetpw.php.

    The easiest thing to actually do is figure out what it is that has changed. Something is different, whether it be the code, the server environment, or the browser.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •