Jump to content

Recommended Posts

Hi all. Ok, I've been trying to fix this for 5 days straight. for some reason, i can't get this code to check the value for email, question and answer against the database. it either gives an error all the time or it allows incorrect data..

 

forgot.php:

 

<?php 
if ($_SERVER["REQUEST_METHOD"] == "POST") { print_r($_POST); }
if ($_SERVER["REQUEST_METHOD"] == "GET") { print_r($_GET); }
error_reporting(E_ALL);
include 'dbc.php';




/******************* ACTIVATION BY FORM**************************/

if(isset($_POST['doReset'])){
if ($_POST['doReset']=='Reset')
{
$err = array();
$msg = array();

foreach($_POST as $key => $value) {
$data[$key] = filter($value);
}

//check if activ code and user is valid as precaution
if(isset($data['user_email'])){
$rs_check = mysql_query("select id from users where user_email='$data[user_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(isset($_POST['user_email'])){
if($_POST['user_email1'] != stripslashes(isEmail($data['user_email']))) {
$err[] = "ERROR - Please enter a valid email"; 
}
}
if(isset($_POST['usr_question'])){
if($_POST['usr_question1'] != stripslashes($data['usr_question'])) {
$err[] = "ERROR - Please enter a valid question"; 
}
}
if(isset($_POST['usr_answer'])){
if($_POST['usr_answer1'] != stripslashes($data['usr_answer'])) {
$err[] = "ERROR - Please enter a valid answer"; 		 
}
}

if(empty($err)) {

$new_pwd = GenPwd();
$pwd_reset = PwdHash($new_pwd);
//$sha1_new = sha1($new);	
//set update sha1 of new password + salt
if(isset($data['user_email']) && isset($data['usr_question']) && isset($data['usr_answer'])){
$rs_activ = mysql_query("update users set pwd='$pwd_reset' WHERE 
					 user_email='$data[user_email]' AND usr_question='$data[usr_question]' AND usr_answer='$data[usr_answer]'") or die(mysql_error());					 
$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);

echo "Here is your new password:<br>\r\n"
.$new_pwd."<br>\r\n";

}
}

//send email

/*$message = 
"Here are your new password details ...\n
User Email: $user_email \n
Passwd: $new_pwd \n

Thank You

Administrator
$host_upper
______________________________________________________
THIS IS AN AUTOMATED RESPONSE. 
***DO NOT RESPOND TO THIS EMAIL****
";

mail($user_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> 
        using the new password.</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 <font Color="#FF0000">*</font></td>
            <td width="64%"><input name="user_email1" type="text" class="required email"  size="25"></td>
          </tr>
          <tr> 
            <td width="38%">Your Secret Question <font Color="#FF0000">*</font></td>
            <td width="66%"><input name="usr_question1" type="text" class="required question" size="25"></td>
          </tr>
          <tr> 
            <td width="38%">Your Secret Answer <font Color="#FF0000">*</font></td>
            <td width="66%"><input name="usr_answer1" type="text" class="required answer" size="25"></td>
          </tr>
          <tr> 
            <td colspan="2"> <div align="center"> 
                <p> 
                  <input name="doReset" type="submit" id="doLogin3" value="Reset"><br><br>
<a href="./register.php">Register</a> | <a href="./login.php">Login</a>
                </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>

 

dbc.php:

 

<?php

/******************** MAIN SETTINGS - PHP LOGIN SCRIPT V2.1 **********************
Please complete wherever marked xxxxxxxxx

/************* MYSQL DATABASE SETTINGS *****************
1. Specify Database name in $dbname
2. MySQL host (localhost or remotehost)
3. MySQL user name with ALL previleges assigned.
4. MySQL password

Note: If you use cpanel, the name will be like account_database
*************************************************************/

define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", "root"); // set database user
define ("DB_PASS","pass"); // set database password
define ("DB_NAME","KOJ_Login"); // set database name

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

/* Registration Type (Automatic or Manual) 
1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 1;  // set 0 or 1

define("COOKIE_TIME_OUT", 1); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password

//define ("ADMIN_NAME", "admin"); // sp

/* Specify user levels */
define ("ADMIN_LEVEL", 6);
define("GURU_CODE_CONSULTANT",5);
define("GAME_CODER",4);
define("GAME_BETATESTER",3);
define("GAME_ARTIST",2);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);



/*************** reCAPTCHA KEYS****************/
$publickey = "6LeEOLwSAAAAAIDSbmqnOpHk_EyMOQpitY526ePJ";
$privatekey = "6LeEOLwSAAAAAJe_5NTiwR0zNzCstCgIPBfpTO-n";


/**** PAGE PROTECT CODE  ********************************
This code protects pages to only logged in users. If users have not logged in then it will redirect to login page.
If you want to add a new page and want to login protect, COPY this from this to END marker.
Remember this code must be placed on very top of any html or php page.
********************************************************/

function get_log($action){
$logfile= './log.php';
$IP = $_SERVER['REMOTE_ADDR'];
$logdetails=  date("F j, Y, g:i a") . ': ' . '<a href=http://dnsstuff.com/tools/city.ch?ip='.$_SERVER['REMOTE_ADDR'].'>'.$_SERVER['REMOTE_ADDR'].'('.gethostbyaddr($_SERVER['REMOTE_ADDR']).')</a> - <b>'.$action.' - ('.basename("./").')'.'</b>\r\n';
$fp = fopen($logfile, "a");
fwrite($fp, $logdetails);
fclose($fp);
}

function page_protect() {
session_start();

global $db; 

/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
    {
        logout();
        exit;
    }
}

// before we allow sessions, we need to check authentication key - ckey and ctime stored in database

/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_name']) ) 
{
if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){
/* we double check cookie expiry time against stored in database */

$cookie_user_id  = filter($_COOKIE['user_id']);
$rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error());
list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
// coookie expiry
if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {

	logout();
	}
/* Security check with untrusted cookies - dont trust value stored in cookie. 		
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/

 if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && isUserID($_COOKIE['user_name']) && $_COOKIE['user_key'] == sha1($ckey)  ) {
 	  session_regenerate_id(); //against session fixation attacks.

	  $_SESSION['user_id'] = $_COOKIE['user_id'];
	  $_SESSION['user_name'] = $_COOKIE['user_name'];
	/* query user level from database instead of storing in cookies */	
	  list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'"));

	  $_SESSION['user_level'] = $user_level;
	  $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
	  
   } else {
   logout();
   }

  } else {
header("Location: login.php");
exit();
}
}
}



function filter($data) {
$data = trim(htmlentities(stripslashes(strip_tags($data))));
//htmlentities(strip_tags($data)));

if (get_magic_quotes_gpc())
	$data = stripslashes($data);

$data = mysql_real_escape_string($data);

return $data;
}



function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}

function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}

function ChopStr($str, $len) 
{
    if (strlen($str) < $len)
        return $str;

    $str = substr($str,0,$len);
    if ($spc_pos = strrpos($str," "))
            $str = substr($str,0,$spc_pos);

    return $str . "...";
}	

function isEmail($email){
  return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}

function isSecretQuestion($question){
if (preg_match('/^[a-z\d_]{5,20}$/i', $question)) {
	return true;
} else {
	return false;
}
}

function isSecretAnswer($answer){
if (preg_match('/^[a-z\d_]{5,20}$/i', $answer)) {
	return true;
} else {
	return false;
}
}

function isUserID($username)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
	return true;
} else {
	return false;
}
}	

function isURL($url) 
{
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
	return true;
} else {
	return false;
}
} 

function checkPwd($x,$y) 
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }

if (strcmp($x,$y) != 0) {
return false;
} 
return true;
}

function GenPwd($length = 7)
{
  $password = "";
  $possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels
  
  $i = 0; 
    
  while ($i < $length) { 

    
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
       
    
    if (!strstr($password, $char)) { 
      $password .= $char;
      $i++;
    }

  }

  return $password;

}

function GenKey($length = 7)
{
  $password = "";
  $possible = "0123456789abcdefghijkmnopqrstuvwxyz"; 
  
  $i = 0; 
    
  while ($i < $length) { 

    
    $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
       
    
    if (!strstr($password, $char)) { 
      $password .= $char;
      $i++;
    }

  }

  return $password;

}


function logout()
{
global $db;
session_start();

if(isset($_SESSION['user_id']) || isset($_COOKIE['user_id'])) {
mysql_query("update `users` 
		set `ckey`= '', `ctime`= '' 
		where `id`='$_SESSION[user_id]' OR  `id` = '$_COOKIE[user_id]'") or die(mysql_error());
}			

//header("Location: login.php");

/************ Delete the sessions****************/
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy(); 

/* Delete the cookies*******************/
setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");

echo "<html>\r\n"
."<head>\r\n"
."<title>Logout</title>\r\n"
."<link href=\"styles.css\" rel=\"stylesheet\" type=\"text/css\">\r\n"
."<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\r\n"
."</head>\r\n"
."<body>\r\n"
."<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\" class=\"main\">\r\n"
."  <tr> \r\n"
."    <td colspan=\"3\"> </td>\r\n"
."  </tr>\r\n"
."  <tr> \r\n"
."    <td width=\"160\" valign=\"top\">\r\n"
."<p>You have been successfully logged out!</p>\r\n"
."<p>Taking you to the main page</p>\r\n"
."     </td>\r\n"
."    <td width=\"196\" valign=\"top\"> </td>\r\n"
."  </tr>\r\n"
."  <tr> \r\n"
."    <td colspan=\"3\"> </td>\r\n"
."  </tr>\r\n"
."</table>\r\n"
."<meta http-equiv=\"refresh\" content=\"4;url=index.php\">\r\n"
."</body>\r\n"
."</html>";

}

// Password and salt generation
function PwdHash($pwd, $salt = null)
{
    if ($salt === null)     {
        $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
    }
    else     {
        $salt = substr($salt, 0, SALT_LENGTH);
    }
    return $salt . sha1($pwd . $salt);
}

function checkAdmin() {

if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}

}

?>

 

EDIT: the prob is:

 

if(isset($_POST['user_email'])){
if($_POST['user_email1'] != stripslashes(isEmail($data['user_email']))) {
$err[] = "ERROR - Please enter a valid email"; 
}
}
if(isset($_POST['usr_question'])){
if($_POST['usr_question1'] != stripslashes($data['usr_question'])) {
$err[] = "ERROR - Please enter a valid question"; 
}
}
if(isset($_POST['usr_answer'])){
if($_POST['usr_answer1'] != stripslashes($data['usr_answer'])) {
$err[] = "ERROR - Please enter a valid answer";        
}
}

if(empty($err)) {

$new_pwd = GenPwd();
$pwd_reset = PwdHash($new_pwd);
//$sha1_new = sha1($new);   
//set update sha1 of new password + salt
if(isset($data['user_email']) && isset($data['usr_question']) && isset($data['usr_answer'])){
$rs_activ = mysql_query("update users set pwd='$pwd_reset' WHERE 
                   user_email='$data[user_email]' AND usr_question='$data[usr_question]' AND usr_answer='$data[usr_answer]'") or die(mysql_error());                
$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);

echo "Here is your new password:<br>\r\n"
.$new_pwd."<br>\r\n";

}
}

Link to comment
https://forums.phpfreaks.com/topic/210849-please-help-error-check-not-working/
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.