Jump to content

trying to match up hash on two pages


silverglade

Recommended Posts

HI, I have a registration script where a password is made with one hash, and a user password reset page that uses another hash. I don't know how to make them the same, as every time I change them, it messes up the code and I get errors.

 

I will comment the parts that I think need changing. Because when I try to log in with the new password that was made by the reset password script, it says "wrong username or password" because either it wasn't updated in the database, or it was updated in a bad way. Any help greatly appreciated.

 

The password email reset code:

 

<?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//THIS IS THE POSSIBLE PROBLEM
$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, ;

//Encrypt $emailpassword in MD5 format for the database
$newpassword = md5($emailpassword);

        // Make a safe query
$newpassword = mysql_real_escape_string($newpassword);
           $query = sprintf("UPDATE 'users' SET 'password' = '$newpassword'
                          WHERE 'email' = '$forgotpassword'");
                   

//Email out the infromation

$site_name = "mysite.COM";
$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>
      <?
}
?>

 

And now for the registration and password creation script

 

<?php

$host		= " ";
$database 	= " ";
$username 	= " ";
$password 	= " ";

mysql_connect($host, $username, $password) or die("Could not connect: " . mysql_error());

mysql_select_db($database);


if ($_POST['form_submitted'] == '1') {
##User is registering, insert data until we can activate it

$activationKey =  mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand();
$username = mysql_real_escape_string($_POST[username]);


$email = mysql_real_escape_string($_POST[email]);
//////////////////////////////////////////////////////////////////////////
$username= $_POST['username'];

     $checkuser = mysql_query("SELECT username FROM users WHERE username='$username'");

        $username_exist = mysql_num_rows($checkuser);

        if($username_exist > 0){
       
   echo "I'm sorry but the username you specified has already been taken.  Please pick         another one.";
        unset($username);
	$sendemail='0';
         }
   ///////////////////////////////////////////////////////////////////////////////////
   
     $email= $_POST['email'];

     $checkemail = mysql_query("SELECT email FROM users WHERE email='$email'");

        $useremail_exist = mysql_num_rows($checkemail);

        if($useremail_exist > 0){
       
   echo "I'm sorry but the email address you specified has already been taken.  Please pick         another one.";
        unset($email);
	$sendemail='0';
         }
	 ////////////////////////////////////////////////////////////////////////////// 

if ( $_POST['password'] == $_POST['password2'] && $username_exists <=0 && $useremail_exist <= 0) {	

$password = sha1($_POST['password']);


$sql="INSERT INTO users (username, password, email, activationkey, status) VALUES ('$username', '$password', '$email', '$activationKey', 'verify')";

$sendemail = '1';

} else {

echo "*Passwords do not match!";
$sendemail='0';
}

if (!mysql_query($sql))

  {

  die('Error: ' . mysql_error());

  }
$_POST['form_submitted'] = '0'; //make form disappear.

if ($sendemail =='1') { 
echo "An email has been sent to $_POST[email] with an activation key. Please check your mail to complete registration.";
}
##Send activation Email

$to      = $_POST[email];

$subject = "  Registration";

$message = "Welcome to our website! verify_user.php?$activationKey\r\rIf this is an error, ignore this email and you will be removed from our mailing list.\r\rRegards,\  Team";

$headers = 'From: noreply@r.com' . "\r\n" .

    'Reply-To: noreply@r.com' . "\r\n" .

    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

} else {

##User isn't registering, check verify code and change activation code to null, status to activated on success

$queryString = $_SERVER['QUERY_STRING'];

$query = "SELECT * FROM users"; 

$result = mysql_query($query) or die(mysql_error());

  /*if*/ while($row = mysql_fetch_array($result)){

    if ($queryString == $row["activationkey"]){
     

  $_POST['form_submitted'] = '2'; //make form disappear.
     

   echo "Congratulations!" . $row["username"] . " is now the proud new owner of an e.com account. Please sign in to the site at  <a href='sign_in.php'>THIS LINK</a>. ";

    $sql=" UPDATE users SET status='activated' WHERE (id = $row[id])";
          //UPDATE users SET activationkey = '',
  
   //$sql="UPDATE users SET activationkey = 'Done-$row[id]', status='activated' WHERE (id = $row[id])";
       if (!mysql_query($sql))

  {

        die('Error: ' . mysql_error());

  }

    }

  }

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-size: large;
font-weight: bold;
}
.style3 {font-size: large}
-->
</style>
</head>

<body>

<?php 

if (!isset ($_POST['form_submitted'])){

echo (' <div align="center"><span class="style3">  Please register. 
  </span> 
<table border="0">
<form action="verify_user.php" method="post" name="register">
<tr><td>Username: <input type="text" name="username" maxlength="20"></td></tr>
<tr><td>Password:<input type="password" name="password" /></td><td>
<tr><td>Confirm password: <input type="password" name="password2" maxlength="20"></td><td>
<tr><td> Email: <input type="text" name="email" /></td></tr>
  
    <input type="hidden" name="form_submitted" value="1"/>  

<tr><td><input type="submit" value="Submit" /></td></tr>
</form>
</table>
</div>'); 

}
if ( $_POST['form_submitted'] =='2'){  
echo (" You may now enter the site!");//echo nothing no form. 
}
?> 

  
</body>

</html>

Link to comment
Share on other sites

Please if anyone can help. This might be easier to read. Here is the code on the registration page to update the database with the password.

 

 

if ( $_POST['password'] == $_POST['password2'] && $username_exists <=0 && $useremail_exist <= 0) {	

$password = sha1($_POST['password']);

 

and here is the page that is the forgot password email reset form, where it either doesn't update to the database or I am doing it wrong.

 

//Generate a RANDOM  Hash for a password
$random_password=sha1(uniqid(rand()));

//Take the first 8 digits and use them as the password we intend to email the user
$emailpassword=substr($random_password, 0, ;

//Encrypt $emailpassword in for the database
$newpassword = sha1($emailpassword);

        // Make a safe query
$newpassword = mysql_real_escape_string($newpassword);
           $query = sprintf("UPDATE 'users' SET 'password' = '$newpassword'
                          WHERE 'email' = '$forgotpassword'");
                   

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.