Jump to content

SalientAnimal

Members
  • Posts

    366
  • Joined

  • Last visited

Posts posted by SalientAnimal

  1. Hi All,

     

    So I managed to get through all the other errors my form was giving me and everything seems to be working as intended. The only problem I'm having now is that when the password gets updated in the table (I have checked to see that the hashed password changes, and it does), the new password does not work.

     

    I am using SHA512 to encrypt my passwords in my table.

     

    Here are all my functions that I currently have for my forms. The lower part (Heading Password Reset) are all the functions pertaining to the form in question:

    <?php
    
    // includes/functions.php -->
    
    //
    //ERROR CHECKING FUNCTIONS - ADD TO PAGES TO CHECK FOR POSSIBLE ERRORS
    //	var_dump(login_check($mysqli));
    //	var_dump($_SESSION); exit; 
    //	var_dump($_POST);exit; 
    
    include_once 'psl-config.php';
    
    function sec_session_start() {
        $session_name = 'sec_session_id';   // Set a custom session name
        $secure = SECURE;
        // This stops JavaScript being able to access the session id.
        $httponly = true;
        // Forces sessions to only use cookies.
        if (ini_set('session.use_only_cookies', 1) === FALSE) {
            header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
            exit();
        }
        // Gets current cookies params.
        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams["lifetime"],
            $cookieParams["path"], 
            $cookieParams["domain"], 
            $secure,
            $httponly);
        // Sets the session name to the one set above.
        session_name($session_name);
        session_start();            // Start the PHP session 
        session_regenerate_id();    // regenerated the session, delete the old one. 
    }
    
    
    
    function login($email, $password, $mysqli) {
        // Using prepared statements means that SQL injection is not possible. 
        if ($stmt = $mysqli->prepare("SELECT id, username, password, email, level, salt 
            FROM members
           WHERE username = ?
            LIMIT 1")) {
            $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
            $stmt->execute();    // Execute the prepared query.
            $stmt->store_result();
    
            // get variables from result.
            $stmt->bind_result($user_id, $username, $db_password, $email, $level, $salt);
            $stmt->fetch();
    
            // hash the password with the unique salt.
            $password = hash('sha512', $password . $salt);
            if ($stmt->num_rows == 1) {
                // If the user exists we check if the account is locked
                // from too many login attempts 
     
                if (checkbrute($user_id, $mysqli) == true) {
                    // Account is locked 
                    // Send an email to user saying their account is locked
                    return false;
                } else {
                    // Check if the password in the database matches
                    // the password the user submitted.
                    if ($db_password == $password) {
                        // Password is correct!
                        // Get the user-agent string of the user.
                        $user_browser = $_SERVER['HTTP_USER_AGENT'];
                        // XSS protection as we might print this value
                        $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                        $_SESSION['user_id'] = $user_id;
                        // XSS protection as we might print this value
                        $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                    "", 
                                                                    $username);
                        $_SESSION['username'] = $username;
                        $_SESSION['login_string'] = hash('sha512',$password . $user_browser);
    					$_SESSION['email'] = $email;
    					$_SESSION['level'] = $level;
    					$_SESSION['session_status'] = $session_status;
                        $mysqli->query("SELECT * FROM login_success WHERE user_id = '$user_id'");
    					if			  (mysql_num_rows($mysqli) > 0)
    						{
    						$mysqli->query("UPDATE login_success SET time = NOW() WHERE user_id = '$user_id'");
    						}
    					else
    						{
    						$mysqli->query("INSERT INTO login_success(user_id, time) VALUES ('$user_id', now()");
    						}
    					//UPDATE login_success SET time = now() where user_id = '$user_id'");							  
                        // Login successful.
                        return true;
                    } else {
                        // Password is not correct
                        // We record this attempt in the database
                        //$now = time();
                        $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                        VALUES ('$user_id', now())");
                        return false;
                    }
                }
            } else {
                // No user exists.
                return false;
            }
        }
    }
    
    
    
    function checkbrute($user_id, $mysqli) {
        // Get timestamp of current time 
        $now = time();
    
        // All login attempts are counted from the past 2 hours. 
        $valid_attempts = $now - (2 * 60 * 60);
    
        if ($stmt = $mysqli->prepare("SELECT time 
                                 FROM login_attempts 
                                 WHERE user_id = ? 
                                AND time > '$valid_attempts'")) {
            $stmt->bind_param('i', $user_id);
    
            // Execute the prepared query. 
            $stmt->execute();
            $stmt->store_result();
    
            // If there have been more than 5 failed logins 
            if ($stmt->num_rows > 5) {
                return true;
            } else {
                return false;
            }
        }
    }
    
    
    
    function login_check($mysqli) 
    	{
        // Check if all session variables are set 
        if (isset($_SESSION['user_id'], 
    			  $_SESSION['username'], 
    			  $_SESSION['login_string'],
    			  $_SESSION['email'],
    			  $_SESSION['level']
    			  //$_SESSION['session_status']
    			  )) 
    	{
    
        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];
    	$email = $_SESSION['email'];
    	$level = $_SESSION['level'];
    	//$status = $_SESSON['session_status'];
    		
    
            // Get the user-agent string of the user.
            $user_browser = $_SERVER['HTTP_USER_AGENT'];
    
            if ($stmt = $mysqli->prepare("SELECT password 
                                          FROM members 
                                          WHERE id = ? LIMIT 1")) {
                // Bind "$user_id" to parameter. 
                $stmt->bind_param('i', $user_id);
                $stmt->execute();   // Execute the prepared query.
                $stmt->store_result();
    
                if ($stmt->num_rows == 1) {
                    // If the user exists get variables from result.
                    $stmt->bind_result($password);
                    $stmt->fetch();
                    $login_check = hash('sha512', $password . $user_browser);
    
                    if ($login_check == $login_string) {
                        // Logged In!!!! 
    					//echo 'logged in';
                        return true;
                    } else {
                        // Not logged in 
    					echo 1;
                        return false;
                    }
                } else {
                    // Not logged in
    					echo 2;
                    return false;
                }
            } else {
                // Not logged in 
    			echo 3;
                return false;
            }
        } else {
            // Not logged in 
    		//echo 4;
            return false;
        }
    }
    
    
    
    function esc_url($url) {
    
        if ('' == $url) {
            return $url;
        }
    
        $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
    
        $strip = array('%0d', '%0a', '%0D', '%0A');
        $url = (string) $url;
    
        $count = 1;
        while ($count) {
            $url = str_replace($strip, '', $url, $count);
       }
    
        $url = str_replace(';//', '://', $url);
    
        $url = htmlentities($url);
    
        $url = str_replace('&', '&', $url);
        $url = str_replace("'", ''', $url);
    
        if ($url[0] !== '/') {
            // We're only interested in relative links from $_SERVER['PHP_SELF']
            return '';
        } else {
            return $url;
        }
    }
    
    
    
    
    
    function crypto_rand_secure($min, $max) {
            $range = $max - $min;
            if ($range < 0) return $min; // not so random...
            $log = log($range, 2);
            $bytes = (int) ($log /  + 1; // length in bytes
            $bits = (int) $log + 1; // length in bits
            $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
            do {
                $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
                $rnd = $rnd & $filter; // discard irrelevant bits
            } while ($rnd >= $range);
            return $min + $rnd;
    }
    
    function getToken($length=32){
        $token = "";
        $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
        $codeAlphabet.= "0123456789";
        for($i=0;$i<$length;$i++){
            $token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
        }
        return $token;
    }
    
    
    
    
    
    
    /* RESTRICTED ACCESS LEVEL MANAGEMENT */
    
    
    	
    	function checkLoginLevel() {
            $allowed = array(
                '0' => array('register.addinfo.php','process/*','includes/*','index.php','index.html'), /* NEW REGISTRATION ACCESS LEVELS */
                '1' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','walkin_form.php','walkin_delete.php'),		/* ACCESS LEVELS FROM RECEPTION */
                '2' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','first-page.php'),
                '3' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','retail_view.php','retail_viewer.php','walkin_form.php','retail_form.php'),
    			'4' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','premier_form.php', 'second-page.php', 'third-page.php'), /* SUPERVISOR ACCESS LEVELS */
                '5' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','premier_form.php', 'second-page.php', 'third-page.php'), /* SUPERVISOR ACCESS LEVELS */
    			'99' => true, /* ADMINISTRATION ACCESS LEVELS */
            );
    
        if(!isset($allowed[$_SESSION['level']])) {
            echo 'Your access level has not been set. Please return to the Login / Registration Page.';
            exit;
        }
    	
    	if($_SESSION['level'] == 0) {
    	header('Location:register.addinfo.php');
    	exit;
    	}
    
        if(is_array($allowed[$_SESSION['level']])) {
    
            $file = $_SERVER["PHP_SELF"];
            $filearray = explode('/', $file);
            $filename = array_pop($filearray);
            $directory = array_pop($filearray);
    
            foreach($allowed[$_SESSION['level']] as $access) {
                if(strpos($access,'*')) {
                    if($access == $directory . '/*') {
                        return true;
                    }
                } elseif($access == $filename) {
                    return true;
                }
            }
        }
    
        if(is_bool($allowed[$_SESSION['level']])) {
            return true;
        }
    
        echo 'You are not authorised to view this page. Please contact your manager to have your access level adjusted';
        exit;
    }
    
    
    
    
    
    //PSSWORD RESET FUNCTIONS
    
    
    
    
    //define(PW_SALT,'(+3%_');
     
    function checkUNEmail($username,$email)
    {
        global $mysqli;
        $error = array('status'=>false,'user_id'=>0);
        if (isset($email) && trim($email) != '') {
            //email was entered
            if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
            {
                $stmt->bind_param('s',trim($email));
                $stmt->execute();
                $stmt->store_result();
                $numRows = $stmt->num_rows();
                $stmt->bind_result($user_id);
                $stmt->fetch();
                $stmt->close();
                if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
            } else { return $error; }
        } elseif (isset($username) && trim($username) != '') {
            //username was entered
            if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
            {
                $stmt->bind_param('s',trim($username));
                $stmt->execute();
                $stmt->store_result();
                $numRows = $stmt->num_rows();
                $stmt->bind_result($user_id);
                $stmt->fetch();
                $stmt->close();
                if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
            } else { return $error; }
        } else {
            //nothing was entered;
            return $error;
        }
    }
    
    
    
    function getSecurityQuestion($user_id)
    {
        global $mysqli;
        $questions = array();
        $questions[0] = "What is your mother's maiden name?";
        $questions[1] = "What city were you born in?";
        $questions[2] = "What is your favorite colour?";
        $questions[3] = "What year did you graduate from High School?";
        $questions[4] = "What is your pet's name?";
        $questions[5] = "What is your favorite model of car?";
        if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($security_q);
            $stmt->fetch();
            $stmt->close();
    		return $security_q;
        } else {
            return false;
        }
    }
     
    function checkSecAnswer($user_id, $security_a)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_a) = ? LIMIT 1"))
        {
            $security_a = strtolower($security_a);
            $stmt->bind_param('is',$user_id, $security_a);
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->close();
            if ($numRows >= 1) { return true; }
        } else {
            return false;
        }
    }
    
    
    
    
    function sendPasswordEmail($user_id)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($username, $email, $pword);
            $stmt->fetch();
            $stmt->close();
            $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
            $expDate = date("Y-m-d H:i:s",$expFormat);
            $security_key =  hash('sha512',$username . '_' . $email . rand(0,10000) .$expDate);
            if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
            {
                $stmt->bind_param('iss',$user_id, $security_key, $expDate);
                $stmt->execute();
                $stmt->close();
                $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://www.oursite.com/forgotPass.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
                $message = "Dear $username,\r\n";
                $message .= "Please visit the following link to reset your password:\r\n";
                $message .= "-----------------------\r\n";
                $message .= "$passwordLink\r\n";
                $message .= "-----------------------\r\n";
                $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
                $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
                $message .= "Thanks,\r\n";
                $message .= "-- Our site team";
                $headers .= "From: Our Site <webmaster@oursite.com
    			
    <script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>> \n";
                $headers .= "To-Sender: \n";
                $headers .= "X-Mailer: PHP\n"; // mailer
                $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>\n"; // Reply address
                $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>\n"; //Return Path for errors
                $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
                $subject = "Your Lost password";
                @mail($email,$subject,$message,$headers);
                return str_replace("\r\n","<br/ >",$message);
            }
        }
    }
    
    
    function checkEmailKey($security_key,$user_id)
    {
        global $mysqli;
        $curDate = date("Y-m-d H:i:s");
        if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
        {
            $stmt->bind_param('sis',$security_key, $user_id, $curDate);
            $stmt->execute();
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows > 0 && $user_id != '')
            {
                return array('status'=>true,'user_id'=>$user_id);
            }
        }
        return false;
    }
     
    function updateUserPassword($user_id, $password, $security_key, $salt)
    {
        global $mysqli;
        if (checkEmailkey($security_key,$user_id) === false) return false;
        if ($stmt = $mysqli->prepare("UPDATE members SET password = ?, salt = ? WHERE id = ?"))
        {
            //$password = hash('sha512',trim($password) . $salt);
    		
    		$password = hash('sha512', $password . $salt);
    
            $stmt->bind_param('sis',$password, $user_id, $salt);
            $stmt->execute();
            $stmt->close();
            $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
            $stmt->bind_param('s',$security_key);
            $stmt->execute();
        }
    }
     
    function getUserName($user_id)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($username);
            $stmt->fetch();
            $stmt->close();
        }
        return $username;
    }
    
    
    
    

    And the actual form is below:

    <?php
    include_once 'db_connect.php';
    include_once 'functions.php';
    include_once 'formatting_includes.php';	
    sec_session_start();
    if (login_check($mysqli) == true) 
    	{
        $logged = 'in';
    	} 
    	
    
    
    $show = 'emailForm'; //which form step to show by default
    if(!isset($_SESSION['lastTime']))
       $_SESSION['lastTime'] = false;
    if (isset($_SESSION['lockout']) && $_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))
    {
        $_SESSION['lockout'] = false;
        $_SESSION['badCount'] = 0;
    }
    if(!isset($_SESSION['lockout']))
       $_SESSION['lockout'] = false;
    if (isset($_POST['subStep']) && !isset($_GET['a']) &&  $_SESSION['lockout'] != true)
    {
        switch($_POST['subStep'])
        {
            case 1:
                //we just submitted an email or username for verification
                $result = checkUNEmail($_POST['username'],$_POST['email']);
                if ($result['status'] == false )
                {
                    $error = true;
                    $show = 'userNotFound';
                } else {
                    $error = false;
                    $show = 'securityForm';
                    $securityUser = $result['id'];
                }
            break;
            case 2:
                //we just submitted the security question for verification
                if ($_POST['user_id'] != "" && $_POST['security_a'] != "")
                {
                    $result = checkSecAnswer($_POST['user_id'],$_POST['security_a']);
                    if ($result == true)
                    {
                        //answer was right
                        $error = false;
                        $show = 'successPage';
                        $passwordMessage = sendPasswordEmail($_POST['user_id']);
                        $_SESSION['badCount'] = 0;
                    } else {
                        //answer was wrong
                        $error = true;
                        $show = 'securityForm';
                        $securityUser = $_POST['user_id'];
                        $_SESSION['badCount']++;
                    }
                } else {
                    $error = true;
                    $show = 'securityForm';
                }
            break;
            case 3:
    		if (!isset($_POST['salt'])) 
    			{
    //If not isset -> set with dumy value 
    			$_POST['salt'] = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE)); 
    } 
    		
                //we are submitting a new password (only for encrypted)
    			if ($_POST['user_id'] == '' || $_POST['security_key'] == '') header("location: ../index.php");
                if (strcmp($_POST['pw0'],$_POST['pw1']) != 0 || trim($_POST['pw0']) == '')
                {
                    $error = true;
                    $show = 'recoverForm';
                } else {
                    $error = false;
                    $show = 'recoverSuccess';
                    updateUserPassword($_POST['user_id'],$_POST['pw0'],$_POST['security_key'], $_POST['salt']);
                }
            break;
        }
    }
    
    elseif (isset($_GET['a']) && $_GET['a'] == 'recover' && $_GET['email'] != "") {
        $show = 'invalidKey';
        $result = checkEmailKey($_GET['email'],urldecode(base64_decode($_GET['u'])));
        if ($result == false)
        {
            $error = true;
            $show = 'invalidKey';
        } elseif ($result['status'] == true) {
            $error = false;
            $show = 'recoverForm';
            $securityUser = $result['user_id'];
        }
    }
    if (isset($_SESSION['badCount']) && $_SESSION['badCount'] >= 3)
    {
        $show = 'speedLimit';
        $_SESSION['lockout'] = true;
        $_SESSION['lastTime'] = '' ? mktime() : $_SESSION['lastTime'];
    }
    ?>
    
    	 
    
    
    <!doctype html>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Password Recovery</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    </head>
    <body>
    
    <?php
    // INCLUDING THE TOP LOGIN / LOGOUT PANEL
    include 'panel.php';
    // INCLUDING THE NAVIGATION MENU
    ?>
    
    <div id="container">
    <div id="content" style="margin-top:-45px;">
    		<img src="../images/logo.png" alt="Altech Autopage"></img>
    
    
    <!-- CREATE THE FORM TO REQUEST THE USER TO SUBMIT DETAILS OF ACCOUNT -->
    
    <?php switch($show) {
        case 'emailForm': ?>
    	<div id="stylized" class="form">
    
    	<h2>Password Recovery</h2>
    
    		<p>Upon registration your password was securly encrypted in our database and it is impossible to actually recover your password. 																		
    		However by filling in the for below, and answering your security question we can allow you to securely reset it. </p>
    
    		<p>Please enter either your registered username or registered e-mail address below to get stared.</p>
    
    		<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
    
    
    		
    			<div class="fieldGroup"><label>Username :
    			<span class="small">Username created when registering</span>
    			</label>
    			<div class="field"><input type="text" name="username" id="username" value="">
    			</div>
    			</div>
    			
    			<br><br>
    			
    			<p align='center' style="color: #ED1C24; font: bold 16px Arial, sans-serif;">-- OR -- </p>
    			
    			<br>
    				
    			<div class="fieldGroup"><label>E-Mail Address :
    			<span class="small">E-Mail Address used when registering</span>
    			</label>
    			<div class="field"><input type="text" name="email" id="email" value="">
    			</div>
    			</div>
    				
            	<input type="hidden" name="subStep" value="1" />
    			<div class="fieldGroup"><input type="button" value="Find User" class="bt_login" onClick="form.submit()"/></div>
    			<div class="clear"></div>
    		</form>
    	</div>
    
    
    <?php break; case 'securityForm': ?>
    
    
    	<div id="stylized" class="form">
    	
    	<h2>Password Recovery</h2>
    
    		<p>Here comes the tricky part where we test your knowledge...</p>
    
    		<p>Please answer the security question below so that we can verify that the correct person is trying to access your account.</p>
    
    		<div class="fieldGroup">
    		<?php if ($error == true) { ?>
    		<span class="error">You have answered the security question incorrectly, please try again. If you are unable to remember the answer to 		your question, please contact your Team Manager.</span>
    		<?php } ?>
    		</div>
    
    		<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
    
    			<div class="fieldGroup"><label>Security Question :
    			<span class="small">Validation Question</span>
    			</label>
    			<div class="field">   <?= getSecurityQuestion($securityUser);?></div></div>
    
    			<br>
    			
    			
    			<div class="fieldGroup"><label>Security Answer :
    			<span class="small">Validation Answer</span>
    			</label>
    			<div class="field"><input type="text" name="security_a" id="security_a" value=""></div></div>
    
            	<input type="hidden" name="subStep" value="2" />
            	<input type="hidden" name="user_id" value="<?= $securityUser; ?>" />
    			<div class="fieldGroup">
    			<input type="button" value="Recover" class="bt_login" onClick="form.submit()" style="margin-left: 150px;"/>										
    			</div>
            	<div class="clear"></div>
        	</form>
    	</div>
     
         
         	<?php break; case 'userNotFound': ?><br>  
    
    	<div id="stylized" class="form">
    	
    	 	<h2>Password Recovery</h2><br>    
    	 	<p>It appears that the username / password you are searching for is not valid,
    	 	please <a href="?">Click here</a> to go back and try again.</p><br>    
    		<div class="fieldGroup"></div> 
    	</div>
    		
    		<?php break; case 'successPage': ?><br>   
    	 	<h2>Password Recovery</h2><br>    
    
    	 	<div class="message"><?= $passwordMessage;?></div><br>    
    	
    
    
    	
    	 	<?php break; case 'recoverForm': ?>
    	<div id="stylized" class="form">
    	
        	<h2>Password Recovery</h2>
        	<p>Welcome back, <?= getUserName($securityUser=='' ? $_POST['user_id'] : $securityUser); ?>.</p>
        	<p>In the fields below, enter your new password.</p>
        	
    		<?php if ($error == true) { ?><span class="error">The new passwords must match and must not be empty.</span><?php } ?>
        	<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
    			<div class="fieldGroup"><label for="pw0">New Password</label><div class="field">
    			<input type="password" class="input" name="pw0" id="pw0" value="" maxlength="20"></div></div>
    			<div class="fieldGroup"><label for="pw1">Confirm Password</label><div class="field">
    			<input type="password" class="input" name="pw1" id="pw1" value="" maxlength="20"></div></div>
    			<input type="hidden" name="subStep" value="3" />
    			<input type="hidden" name="user_id" value="<?= $securityUser=='' ? $_POST['user_id'] : $securityUser; ?>" />
    			<input type="hidden" name="security_key" value="<?= $_GET['email']=='' ? $_POST['security_key'] : $_GET['email']; ?>" />
    			<div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
    			<div class="clear"></div>
    		</form>
    	</div>
    	
        <?php break; case 'invalidsecurity_key': ?>
        <h2>Invalid security_key</h2>
        <p>The security_key that you entered was invalid. Either you did not copy the entire security_key from the email, you are trying to use the security_key after it has expired (3 days after request), or you have already used the security_key in which case it is deactivated.<br /><br /><a href="../index.php">Return</a> to the login page. </p>
        <?php break; case 'recoverSuccess': ?>
        <h2>Password Reset</h2>
        <p>Congratulations! your password has been reset successfully.</p><br /><br /><a href="../index.php">Return</a> to the login page. </p>
        <?php break; case 'speedLimit': ?>
        <h2>Warning</h2>
        <p>You have answered the security question wrong too many times. You will be locked out for 15 minutes, after which you can try again.</p><br /><br /><a href="../index.php">Return</a> to the login page. </p>
        <?php break; }
        ob_flush();
        $mysqli->close();
    ?>
    <br><br><br>
    </div>
    </div>
    </div>
    
    <div id="container">
    <div id="footer" style="margin-top:10px;">
    <footer style="background:#E5E5E5; height:20px">
      <p>Copyright © Altech Autopage 2014 | <a href="mailto:">Contact Us</a>.</p>
      <img src="../images/altron-footer-logo.png" alt="Altron Footer Logo" align="left"></img>
      <img src="../images/altech_bbbee.png" alt="Altech Level 2 BBEE" align="left"></img>
    </footer>
    </div>	
    </div>
    
    <!--PAGE CONTENT-->
    </div>
    </body>
    </html>
    

    I have been playing around with the functions and form code to try and get it working, however I haven't been able to get it to work.

     

  2. The form is updating the database with something, but I am not sure exactly with what, and why it is not working when trying to login with the new details.

     

    What I have done, is I submitted the password to the table un-hashed to check that the correct password is being added, and this is correct. The only other thing that I feel my be cause any problems is the SALT which I have excluded from the script. I would really appreciate some help here.

     

    Here are all the functions that I have, I assume it could be something to do with the login functions and the SALT conflicting, but I'm not entirely sure.

    <?php
    
    // includes/functions.php -->
    
    //
    //ERROR CHECKING FUNCTIONS - ADD TO PAGES TO CHECK FOR POSSIBLE ERRORS
    //	var_dump(login_check($mysqli));
    //	var_dump($_SESSION); exit; 
    //	var_dump($_POST);exit; 
    
    include_once 'psl-config.php';
    
    function sec_session_start() {
        $session_name = 'sec_session_id';   // Set a custom session name
        $secure = SECURE;
        // This stops JavaScript being able to access the session id.
        $httponly = true;
        // Forces sessions to only use cookies.
        if (ini_set('session.use_only_cookies', 1) === FALSE) {
            header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
            exit();
        }
        // Gets current cookies params.
        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams["lifetime"],
            $cookieParams["path"], 
            $cookieParams["domain"], 
            $secure,
            $httponly);
        // Sets the session name to the one set above.
        session_name($session_name);
        session_start();            // Start the PHP session 
        session_regenerate_id();    // regenerated the session, delete the old one. 
    }
    
    
    
    function login($email, $password, $mysqli) {
        // Using prepared statements means that SQL injection is not possible. 
        if ($stmt = $mysqli->prepare("SELECT id, username, password, email, level, salt 
            FROM members
           WHERE username = ?
            LIMIT 1")) {
            $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
            $stmt->execute();    // Execute the prepared query.
            $stmt->store_result();
    
            // get variables from result.
            $stmt->bind_result($user_id, $username, $db_password, $email, $level, $salt);
            $stmt->fetch();
    
            // hash the password with the unique salt.
            $password = hash('sha512', $password . $salt);
            if ($stmt->num_rows == 1) {
                // If the user exists we check if the account is locked
                // from too many login attempts 
     
                if (checkbrute($user_id, $mysqli) == true) {
                    // Account is locked 
                    // Send an email to user saying their account is locked
                    return false;
                } else {
                    // Check if the password in the database matches
                    // the password the user submitted.
                    if ($db_password == $password) {
                        // Password is correct!
                        // Get the user-agent string of the user.
                        $user_browser = $_SERVER['HTTP_USER_AGENT'];
                        // XSS protection as we might print this value
                        $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                        $_SESSION['user_id'] = $user_id;
                        // XSS protection as we might print this value
                        $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                    "", 
                                                                    $username);
                        $_SESSION['username'] = $username;
                        $_SESSION['login_string'] = hash('sha512',$password . $user_browser);
    					$_SESSION['email'] = $email;
    					$_SESSION['level'] = $level;
    					$_SESSION['session_status'] = $session_status;
                        $mysqli->query("SELECT * FROM login_success WHERE user_id = '$user_id'");
    					if			  (mysql_num_rows($mysqli) > 0)
    						{
    						$mysqli->query("UPDATE login_success SET time = NOW() WHERE user_id = '$user_id'");
    						}
    					else
    						{
    						$mysqli->query("INSERT INTO login_success(user_id, time) VALUES ('$user_id', now()");
    						}
    					//UPDATE login_success SET time = now() where user_id = '$user_id'");							  
                        // Login successful.
                        return true;
                    } else {
                        // Password is not correct
                        // We record this attempt in the database
                        //$now = time();
                        $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                        VALUES ('$user_id', now())");
                        return false;
                    }
                }
            } else {
                // No user exists.
                return false;
            }
        }
    }
    
    
    
    function checkbrute($user_id, $mysqli) {
        // Get timestamp of current time 
        $now = time();
    
        // All login attempts are counted from the past 2 hours. 
        $valid_attempts = $now - (2 * 60 * 60);
    
        if ($stmt = $mysqli->prepare("SELECT time 
                                 FROM login_attempts 
                                 WHERE user_id = ? 
                                AND time > '$valid_attempts'")) {
            $stmt->bind_param('i', $user_id);
    
            // Execute the prepared query. 
            $stmt->execute();
            $stmt->store_result();
    
            // If there have been more than 5 failed logins 
            if ($stmt->num_rows > 5) {
                return true;
            } else {
                return false;
            }
        }
    }
    
    
    
    function login_check($mysqli) 
    	{
        // Check if all session variables are set 
        if (isset($_SESSION['user_id'], 
    			  $_SESSION['username'], 
    			  $_SESSION['login_string'],
    			  $_SESSION['email'],
    			  $_SESSION['level']
    			  //$_SESSION['session_status']
    			  )) 
    	{
    
        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];
    	$email = $_SESSION['email'];
    	$level = $_SESSION['level'];
    	//$status = $_SESSON['session_status'];
    		
    
            // Get the user-agent string of the user.
            $user_browser = $_SERVER['HTTP_USER_AGENT'];
    
            if ($stmt = $mysqli->prepare("SELECT password 
                                          FROM members 
                                          WHERE id = ? LIMIT 1")) {
                // Bind "$user_id" to parameter. 
                $stmt->bind_param('i', $user_id);
                $stmt->execute();   // Execute the prepared query.
                $stmt->store_result();
    
                if ($stmt->num_rows == 1) {
                    // If the user exists get variables from result.
                    $stmt->bind_result($password);
                    $stmt->fetch();
                    $login_check = hash('sha512', $password . $user_browser);
    
                    if ($login_check == $login_string) {
                        // Logged In!!!! 
    					//echo 'logged in';
                        return true;
                    } else {
                        // Not logged in 
    					echo 1;
                        return false;
                    }
                } else {
                    // Not logged in
    					echo 2;
                    return false;
                }
            } else {
                // Not logged in 
    			echo 3;
                return false;
            }
        } else {
            // Not logged in 
    		//echo 4;
            return false;
        }
    }
    
    
    
    function esc_url($url) {
    
        if ('' == $url) {
            return $url;
        }
    
        $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
    
        $strip = array('%0d', '%0a', '%0D', '%0A');
        $url = (string) $url;
    
        $count = 1;
        while ($count) {
            $url = str_replace($strip, '', $url, $count);
       }
    
        $url = str_replace(';//', '://', $url);
    
        $url = htmlentities($url);
    
        $url = str_replace('&', '&', $url);
        $url = str_replace("'", ''', $url);
    
        if ($url[0] !== '/') {
            // We're only interested in relative links from $_SERVER['PHP_SELF']
            return '';
        } else {
            return $url;
        }
    }
    
    
    
    
    
    function crypto_rand_secure($min, $max) {
            $range = $max - $min;
            if ($range < 0) return $min; // not so random...
            $log = log($range, 2);
            $bytes = (int) ($log /  + 1; // length in bytes
            $bits = (int) $log + 1; // length in bits
            $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
            do {
                $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
                $rnd = $rnd & $filter; // discard irrelevant bits
            } while ($rnd >= $range);
            return $min + $rnd;
    }
    
    function getToken($length=32){
        $token = "";
        $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
        $codeAlphabet.= "0123456789";
        for($i=0;$i<$length;$i++){
            $token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
        }
        return $token;
    }
    
    
    
    
    
    
    /* RESTRICTED ACCESS LEVEL MANAGEMENT */
    
    
    	
    	function checkLoginLevel() {
            $allowed = array(
                '0' => array('register.addinfo.php','process/*','includes/*','index.php','index.html'), /* NEW REGISTRATION ACCESS LEVELS */
                '1' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','walkin_form.php','walkin_delete.php'),		/* ACCESS LEVELS FROM RECEPTION */
                '2' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','first-page.php'),
                '3' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','retail_view.php','retail_viewer.php','walkin_form.php','retail_form.php'),
    			'4' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','premier_form.php', 'second-page.php', 'third-page.php'), /* SUPERVISOR ACCESS LEVELS */
                '5' => array('register.addinfo.php','process/*','includes/*','index.php','index.html','home.php','premier_form.php', 'second-page.php', 'third-page.php'), /* SUPERVISOR ACCESS LEVELS */
    			'99' => true, /* ADMINISTRATION ACCESS LEVELS */
            );
    
        if(!isset($allowed[$_SESSION['level']])) {
            echo 'Your access level has not been set. Please return to the Login / Registration Page.';
            exit;
        }
    	
    	if($_SESSION['level'] == 0) {
    	header('Location:register.addinfo.php');
    	exit;
    	}
    
        if(is_array($allowed[$_SESSION['level']])) {
    
            $file = $_SERVER["PHP_SELF"];
            $filearray = explode('/', $file);
            $filename = array_pop($filearray);
            $directory = array_pop($filearray);
    
            foreach($allowed[$_SESSION['level']] as $access) {
                if(strpos($access,'*')) {
                    if($access == $directory . '/*') {
                        return true;
                    }
                } elseif($access == $filename) {
                    return true;
                }
            }
        }
    
        if(is_bool($allowed[$_SESSION['level']])) {
            return true;
        }
    
        echo 'You are not authorised to view this page. Please contact your manager to have your access level adjusted';
        exit;
    }
    
    
    
    
    
    //PSSWORD RESET FUNCTIONS
    
    
    
    
    //define(PW_SALT,'(+3%_');
     
    function checkUNEmail($username,$email)
    {
        global $mysqli;
        $error = array('status'=>false,'user_id'=>0);
        if (isset($email) && trim($email) != '') {
            //email was entered
            if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
            {
                $stmt->bind_param('s',trim($email));
                $stmt->execute();
                $stmt->store_result();
                $numRows = $stmt->num_rows();
                $stmt->bind_result($user_id);
                $stmt->fetch();
                $stmt->close();
                if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
            } else { return $error; }
        } elseif (isset($username) && trim($username) != '') {
            //username was entered
            if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
            {
                $stmt->bind_param('s',trim($username));
                $stmt->execute();
                $stmt->store_result();
                $numRows = $stmt->num_rows();
                $stmt->bind_result($user_id);
                $stmt->fetch();
                $stmt->close();
                if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
            } else { return $error; }
        } else {
            //nothing was entered;
            return $error;
        }
    }
    
    
    
    function getSecurityQuestion($user_id)
    {
        global $mysqli;
        $questions = array();
        $questions[0] = "What is your mother's maiden name?";
        $questions[1] = "What city were you born in?";
        $questions[2] = "What is your favorite colour?";
        $questions[3] = "What year did you graduate from High School?";
        $questions[4] = "What is your pet's name?";
        $questions[5] = "What is your favorite model of car?";
        if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($security_q);
            $stmt->fetch();
            $stmt->close();
    		return $security_q;
        } else {
            return false;
        }
    }
     
    function checkSecAnswer($user_id, $security_a)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_a) = ? LIMIT 1"))
        {
            $security_a = strtolower($security_a);
            $stmt->bind_param('is',$user_id, $security_a);
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->close();
            if ($numRows >= 1) { return true; }
        } else {
            return false;
        }
    }
    
    
    
    
    function sendPasswordEmail($user_id)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($username, $email, $pword);
            $stmt->fetch();
            $stmt->close();
            $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
            $expDate = date("Y-m-d H:i:s",$expFormat);
            $security_key =  hash('sha512',$username . '_' . $email . rand(0,10000) .$expDate . $salt);
            if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
            {
                $stmt->bind_param('iss',$user_id, $security_key, $expDate);
                $stmt->execute();
                $stmt->close();
                $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://www.oursite.com/forgotPass.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
                $message = "Dear $username,\r\n";
                $message .= "Please visit the following link to reset your password:\r\n";
                $message .= "-----------------------\r\n";
                $message .= "$passwordLink\r\n";
                $message .= "-----------------------\r\n";
                $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
                $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
                $message .= "Thanks,\r\n";
                $message .= "-- Our site team";
                $headers .= "From: Our Site <webmaster@oursite.com
    			
    <script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>> \n";
                $headers .= "To-Sender: \n";
                $headers .= "X-Mailer: PHP\n"; // mailer
                $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>\n"; // Reply address
                $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>\n"; //Return Path for errors
                $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
                $subject = "Your Lost password";
                @mail($email,$subject,$message,$headers);
                return str_replace("\r\n","<br/ >",$message);
            }
        }
    }
    
    
    function checkEmailKey($security_key,$user_id)
    {
        global $mysqli;
        $curDate = date("Y-m-d H:i:s");
        if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
        {
            $stmt->bind_param('sis',$security_key, $user_id, $curDate);
            $stmt->execute();
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows > 0 && $user_id != '')
            {
                return array('status'=>true,'user_id'=>$user_id);
            }
        }
        return false;
    }
     
    function updateUserPassword($user_id, $password, $security_key)
    {
        global $mysqli;
        if (checkEmailkey($security_key,$user_id) === false) return false;
        if ($stmt = $mysqli->prepare("UPDATE members SET password = ? WHERE id = ?"))
        {
            $password = hash('sha512',trim($password) . $salt);
            $stmt->bind_param('si',$password,$user_id);
            $stmt->execute();
            $stmt->close();
            $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
            $stmt->bind_param('s',$security_key);
            $stmt->execute();
        }
    }
     
    function getUserName($user_id)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($username);
            $stmt->fetch();
            $stmt->close();
        }
        return $username;
    }
    
    
    
    
  3. Ok, after spending an entire day on this, I eventually got the form to generate. The last issue I have is the password that is being updated into the database table now does not work.

     

    This is the last part I need to get working to get my password reset form working.

     

    Here is the code that is currently working for me:

     

    Password Reset Functions:

    //PSSWORD RESET FUNCTIONS
    
    
    
    
    //define(PW_SALT,'(+3%_');
     
    function checkUNEmail($username,$email)
    {
        global $mysqli;
        $error = array('status'=>false,'user_id'=>0);
        if (isset($email) && trim($email) != '') {
            //email was entered
            if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
            {
                $stmt->bind_param('s',trim($email));
                $stmt->execute();
                $stmt->store_result();
                $numRows = $stmt->num_rows();
                $stmt->bind_result($user_id);
                $stmt->fetch();
                $stmt->close();
                if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
            } else { return $error; }
        } elseif (isset($username) && trim($username) != '') {
            //username was entered
            if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
            {
                $stmt->bind_param('s',trim($username));
                $stmt->execute();
                $stmt->store_result();
                $numRows = $stmt->num_rows();
                $stmt->bind_result($user_id);
                $stmt->fetch();
                $stmt->close();
                if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
            } else { return $error; }
        } else {
            //nothing was entered;
            return $error;
        }
    }
    
    
    
    function getSecurityQuestion($user_id)
    {
        global $mysqli;
        $questions = array();
        $questions[0] = "What is your mother's maiden name?";
        $questions[1] = "What city were you born in?";
        $questions[2] = "What is your favorite colour?";
        $questions[3] = "What year did you graduate from High School?";
        $questions[4] = "What is your pet's name?";
        $questions[5] = "What is your favorite model of car?";
        if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($security_q);
            $stmt->fetch();
            $stmt->close();
    		return $security_q;
        } else {
            return false;
        }
    }
     
    function checkSecAnswer($user_id, $security_a)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_a) = ? LIMIT 1"))
        {
            $security_a = strtolower($security_a);
            $stmt->bind_param('is',$user_id, $security_a);
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->close();
            if ($numRows >= 1) { return true; }
        } else {
            return false;
        }
    }
    
    
    
    
    function sendPasswordEmail($user_id)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($username, $email, $pword);
            $stmt->fetch();
            $stmt->close();
            $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
            $expDate = date("Y-m-d H:i:s",$expFormat);
            $security_key =  hash('sha512',$username . '_' . $email . rand(0,10000) .$expDate . PW_SALT);
            if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
            {
                $stmt->bind_param('iss',$user_id, $security_key, $expDate);
                $stmt->execute();
                $stmt->close();
                $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://www.oursite.com/forgotPass.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
                $message = "Dear $username,\r\n";
                $message .= "Please visit the following link to reset your password:\r\n";
                $message .= "-----------------------\r\n";
                $message .= "$passwordLink\r\n";
                $message .= "-----------------------\r\n";
                $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
                $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
                $message .= "Thanks,\r\n";
                $message .= "-- Our site team";
                $headers .= "From: Our Site <webmaster@oursite.com
    			
    <script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>> \n";
                $headers .= "To-Sender: \n";
                $headers .= "X-Mailer: PHP\n"; // mailer
                $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>\n"; // Reply address
                $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>\n"; //Return Path for errors
                $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
                $subject = "Your Lost password";
                @mail($email,$subject,$message,$headers);
                return str_replace("\r\n","<br/ >",$message);
            }
        }
    }
    
    
    function checkEmailKey($security_key,$user_id)
    {
        global $mysqli;
        $curDate = date("Y-m-d H:i:s");
        if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
        {
            $stmt->bind_param('sis',$security_key, $user_id, $curDate);
            $stmt->execute();
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows > 0 && $user_id != '')
            {
                return array('status'=>true,'user_id'=>$user_id);
            }
        }
        return false;
    }
     
    function updateUserPassword($user_id, $password, $security_key)
    {
        global $mysqli;
        if (checkEmailkey($security_key,$user_id) === false) return false;
        if ($stmt = $mysqli->prepare("UPDATE members SET password = ? WHERE id = ?"))
        {
            $password = hash('sha512',trim($password));
            $stmt->bind_param('si',$password,$user_id);
            $stmt->execute();
            $stmt->close();
            $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
            $stmt->bind_param('s',$security_key);
            $stmt->execute();
        }
    }
     
    function getUserName($user_id)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($username);
            $stmt->fetch();
            $stmt->close();
        }
        return $username;
    }
    
    

    Password Reset Form:

    <?php
    include_once 'db_connect.php';
    include_once 'functions.php';
    include_once 'formatting_includes.php';	
    sec_session_start();
    if (login_check($mysqli) == true) 
    	{
        $logged = 'in';
    	} 
    	
    
    
    $show = 'emailForm'; //which form step to show by default
    if(!isset($_SESSION['lastTime']))
       $_SESSION['lastTime'] = false;
    if (isset($_SESSION['lockout']) && $_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))
    {
        $_SESSION['lockout'] = false;
        $_SESSION['badCount'] = 0;
    }
    if(!isset($_SESSION['lockout']))
       $_SESSION['lockout'] = false;
    if (isset($_POST['subStep']) && !isset($_GET['a']) &&  $_SESSION['lockout'] != true)
    {
        switch($_POST['subStep'])
        {
            case 1:
                //we just submitted an email or username for verification
                $result = checkUNEmail($_POST['username'],$_POST['email']);
                if ($result['status'] == false )
                {
                    $error = true;
                    $show = 'userNotFound';
                } else {
                    $error = false;
                    $show = 'securityForm';
                    $securityUser = $result['id'];
                }
            break;
            case 2:
                //we just submitted the security question for verification
                if ($_POST['user_id'] != "" && $_POST['security_a'] != "")
                {
                    $result = checkSecAnswer($_POST['user_id'],$_POST['security_a']);
                    if ($result == true)
                    {
                        //answer was right
                        $error = false;
                        $show = 'successPage';
                        $passwordMessage = sendPasswordEmail($_POST['user_id']);
                        $_SESSION['badCount'] = 0;
                    } else {
                        //answer was wrong
                        $error = true;
                        $show = 'securityForm';
                        $securityUser = $_POST['user_id'];
                        $_SESSION['badCount']++;
                    }
                } else {
                    $error = true;
                    $show = 'securityForm';
                }
            break;
            case 3:
                //we are submitting a new password (only for encrypted)
                if ($_POST['user_id'] == '' || $_POST['security_key'] == '') header("location: ../index.php");
                if (strcmp($_POST['pw0'],$_POST['pw1']) != 0 || trim($_POST['pw0']) == '')
                {
                    $error = true;
                    $show = 'recoverForm';
                } else {
                    $error = false;
                    $show = 'recoverSuccess';
                    updateUserPassword($_POST['user_id'],$_POST['pw0'],$_POST['security_key']);
                }
            break;
        }
    }
    
    elseif (isset($_GET['a']) && $_GET['a'] == 'recover' && $_GET['email'] != "") {
        $show = 'invalidKey';
        $result = checkEmailKey($_GET['email'],urldecode(base64_decode($_GET['u'])));
        if ($result == false)
        {
            $error = true;
            $show = 'invalidKey';
        } elseif ($result['status'] == true) {
            $error = false;
            $show = 'recoverForm';
            $securityUser = $result['user_id'];
        }
    }
    if (isset($_SESSION['badCount']) && $_SESSION['badCount'] >= 3)
    {
        $show = 'speedLimit';
        $_SESSION['lockout'] = true;
        $_SESSION['lastTime'] = '' ? mktime() : $_SESSION['lastTime'];
    }
    ?>
    
    	 
    
    
    <!doctype html>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Password Recovery</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    </head>
    <body>
    
    <?php
    // INCLUDING THE TOP LOGIN / LOGOUT PANEL
    include 'panel.php';
    // INCLUDING THE NAVIGATION MENU
    ?>
    
    <div id="container">
    <div id="content" style="margin-top:-45px;">
    		<img src="../images/logo.png" alt="Altech Autopage"></img>
    
    
    <!-- CREATE THE FORM TO REQUEST THE USER TO SUBMIT DETAILS OF ACCOUNT -->
    
    <?php switch($show) {
        case 'emailForm': ?>
    	<div id="stylized" class="form">
    
    	<h2>Password Recovery</h2>
    
    		<p>Upon registration your password was securly encrypted in our database and it is impossible to actually recover your password. 																		
    		However by filling in the for below, and answering your security question we can allow you to securely reset it. </p>
    
    		<p>Please enter either your registered username or registered e-mail address below to get stared.</p>
    
    		<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
    
    
    		
    			<div class="fieldGroup"><label>Username :
    			<span class="small">Username created when registering</span>
    			</label>
    			<div class="field"><input type="text" name="username" id="username" value="">
    			</div>
    			</div>
    			
    			<br><br>
    			
    			<p align='center' style="color: #ED1C24; font: bold 16px Arial, sans-serif;">-- OR -- </p>
    			
    			<br>
    				
    			<div class="fieldGroup"><label>E-Mail Address :
    			<span class="small">E-Mail Address used when registering</span>
    			</label>
    			<div class="field"><input type="text" name="email" id="email" value="">
    			</div>
    			</div>
    				
            	<input type="hidden" name="subStep" value="1" />
    			<div class="fieldGroup"><input type="button" value="Find User" class="bt_login" onClick="form.submit()"/></div>
    			<div class="clear"></div>
    		</form>
    	</div>
    
    
    <?php break; case 'securityForm': ?>
    
    
    	<div id="stylized" class="form">
    	
    	<h2>Password Recovery</h2>
    
    		<p>Here comes the tricky part where we test your knowledge...</p>
    
    		<p>Please answer the security question below so that we can verify that the correct person is trying to access your account.</p>
    
    		<div class="fieldGroup">
    		<?php if ($error == true) { ?>
    		<span class="error">You have answered the security question incorrectly, please try again. If you are unable to remember the answer to 		your question, please contact your Team Manager.</span>
    		<?php } ?>
    		</div>
    
    		<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
    
    			<div class="fieldGroup"><label>Security Question :
    			<span class="small">Validation Question</span>
    			</label>
    			<div class="field">   <?= getSecurityQuestion($securityUser);?></div></div>
    
    			<br>
    			
    			
    			<div class="fieldGroup"><label>Security Answer :
    			<span class="small">Validation Answer</span>
    			</label>
    			<div class="field"><input type="text" name="security_a" id="security_a" value=""></div></div>
    
            	<input type="hidden" name="subStep" value="2" />
            	<input type="hidden" name="user_id" value="<?= $securityUser; ?>" />
    			<div class="fieldGroup">
    			<input type="button" value="Recover" class="bt_login" onClick="form.submit()" style="margin-left: 150px;"/>										
    			</div>
            	<div class="clear"></div>
        	</form>
    	</div>
     
         
         	<?php break; case 'userNotFound': ?><br>  
    
    	<div id="stylized" class="form">
    	
    	 	<h2>Password Recovery</h2><br>    
    	 	<p>It appears that the username / password you are searching for is not valid,
    	 	please <a href="?">Click here</a> to go back and try again.</p><br>    
    		<div class="fieldGroup"></div> 
    	</div>
    		
    		<?php break; case 'successPage': ?><br>   
    	 	<h2>Password Recovery</h2><br>    
    
    	 	<div class="message"><?= $passwordMessage;?></div><br>    
    	
    
    
    	
    	 	<?php break; case 'recoverForm': ?>
    	<div id="stylized" class="form">
    	
        	<h2>Password Recovery</h2>
        	<p>Welcome back, <?= getUserName($securityUser=='' ? $_POST['user_id'] : $securityUser); ?>.</p>
        	<p>In the fields below, enter your new password.</p>
        	
    		<?php if ($error == true) { ?><span class="error">The new passwords must match and must not be empty.</span><?php } ?>
        	<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
    			<div class="fieldGroup"><label for="pw0">New Password</label><div class="field">
    			<input type="password" class="input" name="pw0" id="pw0" value="" maxlength="20"></div></div>
    			<div class="fieldGroup"><label for="pw1">Confirm Password</label><div class="field">
    			<input type="password" class="input" name="pw1" id="pw1" value="" maxlength="20"></div></div>
    			<input type="hidden" name="subStep" value="3" />
    			<input type="hidden" name="user_id" value="<?= $securityUser=='' ? $_POST['user_id'] : $securityUser; ?>" />
    			<input type="hidden" name="security_key" value="<?= $_GET['email']=='' ? $_POST['security_key'] : $_GET['email']; ?>" />
    			<div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
    			<div class="clear"></div>
    		</form>
    	</div>
    	
        <?php break; case 'invalidsecurity_key': ?>
        <h2>Invalid security_key</h2>
        <p>The security_key that you entered was invalid. Either you did not copy the entire security_key from the email, you are trying to use the security_key after it has expired (3 days after request), or you have already used the security_key in which case it is deactivated.<br /><br /><a href="../index.php">Return</a> to the login page. </p>
        <?php break; case 'recoverSuccess': ?>
        <h2>Password Reset</h2>
        <p>Congratulations! your password has been reset successfully.</p><br /><br /><a href="../index.php">Return</a> to the login page. </p>
        <?php break; case 'speedLimit': ?>
        <h2>Warning</h2>
        <p>You have answered the security question wrong too many times. You will be locked out for 15 minutes, after which you can try again.</p><br /><br /><a href="../index.php">Return</a> to the login page. </p>
        <?php break; }
        ob_flush();
        $mysqli->close();
    ?>
    <br><br><br>
    </div>
    </div>
    </div>
    
    <div id="container">
    <div id="footer" style="margin-top:10px;">
    <footer style="background:#E5E5E5; height:20px">
      <p>Copyright © Altech Autopage 2014 | <a href="mailto:lclaassen@autopage.altech.co.za">Contact Us</a>.</p>
      <img src="../images/altron-footer-logo.png" alt="Altron Footer Logo" align="left"></img>
      <img src="../images/altech_bbbee.png" alt="Altech Level 2 BBEE" align="left"></img>
    </footer>
    </div>	
    </div>
    
    <!--PAGE CONTENT-->
    </div>
    </body>
    </html>
    

    I am not getting any error message. I get my last message that says:

     

    Congratulations! your password has been reset successfully.


    Return to the login page.

     

     

     

     

     

     

     

     

     

    Please I need some help again :-).... Thanks.

  4. Another problem I picked up since I changed all the 

     

    md5(

    to

     

    hash('sha512',

     

    my reset form is no longer generating.

     

     

    I should of been more specific here. There entire form works, up until the point when you click on the link. This is when the form doesn't generate.

  5. I wanted to ask you, is it necessary to use the PW_SALT in my password reset form?

     

    Also one of the other errors I picked up is should I enter my Security Answer incorrectly the first time, it will not accept even the correct answer on a second / third attempt. The error I get when this happens is again an undefined variable error. What I don't understand is that I define this earlier in the page if I'm not mistaken?

    Notice: Undefined variable: securityUser in \htdocs\includes\resetpwd.php on line 181
    

    Here is line 181 and a few lines prior to it (181 is the last line)

    <div class="fieldGroup">
    <?php if ($error == true) { ?><span class="error">You have answered the security question incorrectly, please try again. If you are unable to remember the answer to your question, please contact your Team Manager.</span><?php } ?></div>
    
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
    
    			<div class="fieldGroup"><label>Security Question :
    			<span class="small">Validation Question</span>
    			</label>
    			<div class="field">   <?= getSecurityQuestion($securityUser);?></div></div>
    

    Thanks.

  6. I managed to get the form working. There are just a few problems that still exist:

     

    1. The source code encodes the password / new password to MD5, however I am using SHA512, how do I change this to accommodate the different encryption?
    2. I am still getting a few errors on my form that I am not sure how to fix:
    • Notice: Undefined index: lockout in C:\autopage_auxilium\htdocs\includes\resetpwd.php on line 19
      LINE 19
      if (isset($_POST['subStep']) && !isset($_GET['a']) &&  $_SESSION['lockout'] != true)

    • Notice: Use of undefined constant PW_SALT - assumed 'PW_SALT' in C:\autopage_auxilium\htdocs\includes\functions.php on line 429
      LINE 429
      $security_key = md5($username . '_' . $email . rand(0,10000) .$expDate . PW_SALT);

    • Notice: Undefined variable: headers in C:\autopage_auxilium\htdocs\includes\functions.php on line 451
      LINE 451
      </script>> \n";
                  $headers .= "To-Sender: \n";
                  $headers .= "X-Mailer: PHP\n"; // mailer
                  $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>

      Could this be because I am not sending an e-mail? But rather displaying the message to the user provided they answer the question correctly.

  7. Hi All,

    I am busy working on my password reset form. And I was fortunate enough to find the source code to do this, how ever I am having a few problems with the source code. When access the reset password page I ge the following two error messages:

    Notice: Undefined index: lockout in C:\htdocs\includes\resetpwd.php on line 14
    Notice: Undefined index: badCount in C:\htdocs\includes\resetpwd.php on line 89

    Line 14:
    if ($_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))

    Line 89:
    if ($_SESSION['badCount'] >= 3)

    Then when entering my username the page display as intended except for the 3 error messages:

    Notice: Undefined index: lockout in C:\htdocs\includes\resetpwd.php on line 14
    Notice: Undefined index: lockout in C:\htdocs\includes\resetpwd.php on line 19
    Notice: Undefined index: badCount in C:\htdocs\includes\resetpwd.php on line 89
    Notice: Undefined index: What is your pet's name? in C:\autopage_auxilium\htdocs\includes\functions.php on line 389

    Line 19:
    if (isset($_POST['subStep']) && !isset($_GET['a']) && $_SESSION['lockout'] != true)

    Line 389:
    return $questions[$security_q];

    Line 14 / 89 are the same as aboce as they come from the same file.

    Despite answering the security question correctly, the form does not accept it and I do not get to a point to reset.
    Any help will be appreciated.

     

     

    Here is the code to the two files:

    Password Reset Functions

    //PSSWORD RESET FUNCTIONS
    
    
    
    
    //define(PW_SALT,'(+3%_');
     
    function checkUNEmail($username,$email)
    {
        global $mysqli;
        $error = array('status'=>false,'user_id'=>0);
        if (isset($email) && trim($email) != '') {
            //email was entered
            if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE email = ? LIMIT 1"))
            {
                $stmt->bind_param('s',trim($email));
                $stmt->execute();
                $stmt->store_result();
                $numRows = $stmt->num_rows();
                $stmt->bind_result($user_id);
                $stmt->fetch();
                $stmt->close();
                if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
            } else { return $error; }
        } elseif (isset($username) && trim($username) != '') {
            //username was entered
            if ($stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1"))
            {
                $stmt->bind_param('s',trim($username));
                $stmt->execute();
                $stmt->store_result();
                $numRows = $stmt->num_rows();
                $stmt->bind_result($user_id);
                $stmt->fetch();
                $stmt->close();
                if ($numRows >= 1) return array('status'=>true,'id'=>$user_id);
            } else { return $error; }
        } else {
            //nothing was entered;
            return $error;
        }
    }
    
    
    
    function getSecurityQuestion($user_id)
    {
        global $mysqli;
        $questions = array();
        $questions[0] = "What is your mother's maiden name?";
        $questions[1] = "What city were you born in?";
        $questions[2] = "What is your favorite colour?";
        $questions[3] = "What year did you graduate from High School?";
        $questions[4] = "What is your pet's name?";
        $questions[5] = "What is your favorite model of car?";
        if ($stmt = $mysqli->prepare("SELECT security_q FROM members WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($security_q);
            $stmt->fetch();
            $stmt->close();
            return $questions[$security_q];
        } else {
            return false;
        }
    }
     
    function checkSecAnswer($user_id, $security_a)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ? AND LOWER(security_q) = ? LIMIT 1"))
        {
            $security_a = strtolower($security_a);
            $stmt->bind_param('is',$user_id, $security_a);
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->close();
            if ($numRows >= 1) { return true; }
        } else {
            return false;
        }
    }
    
    
    
    
    function sendPasswordEmail($user_id)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username, email, password FROM members WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($username, $email, $pword);
            $stmt->fetch();
            $stmt->close();
            $expFormat = mktime(date("H"), date("i"), date("s"), date("m")  , date("d")+3, date("Y"));
            $expDate = date("Y-m-d H:i:s",$expFormat);
            $security_key = md5($username . '_' . $email . rand(0,10000) .$expDate . PW_SALT);
            if ($stmt = $mysqli->prepare("INSERT INTO password_reset (user_id, security_key, expiry_date) VALUES (?,?,?)"))
            {
                $stmt->bind_param('iss',$user_id, $security_key, $expDate);
                $stmt->execute();
                $stmt->close();
                $passwordLink = "<a href=\"?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "\">http://www.oursite.com/forgotPass.php?a=recover&email=" . $security_key . "&u=" . urlencode(base64_encode($user_id)) . "</a>";
                $message = "Dear $username,\r\n";
                $message .= "Please visit the following link to reset your password:\r\n";
                $message .= "-----------------------\r\n";
                $message .= "$passwordLink\r\n";
                $message .= "-----------------------\r\n";
                $message .= "Please be sure to copy the entire link into your browser. The link will expire after 3 days for security reasons.\r\n\r\n";
                $message .= "If you did not request this forgotten password email, no action is needed, your password will not be reset as long as the link above is not visited. However, you may want to log into your account and change your security password and answer, as someone may have guessed it.\r\n\r\n";
                $message .= "Thanks,\r\n";
                $message .= "-- Our site team";
                $headers .= "From: Our Site <webmaster@oursite.com
    			
    <script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>> \n";
                $headers .= "To-Sender: \n";
                $headers .= "X-Mailer: PHP\n"; // mailer
                $headers .= "Reply-To: webmaster@oursite.com<script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>\n"; // Reply address
                $headers .= "Return-Path: webmaster@oursite.com<script type='text/javascript'>
    /* <![CDATA[ */
    (function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName('script');l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
    /* ]]> */
    </script>\n"; //Return Path for errors
                $headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
                $subject = "Your Lost password";
                @mail($email,$subject,$message,$headers);
                return str_replace("\r\n","<br/ >",$message);
            }
        }
    }
    
    
    function checkEmailKey($security_key,$user_id)
    {
        global $mysqli;
        $curDate = date("Y-m-d H:i:s");
        if ($stmt = $mysqli->prepare("SELECT user_id FROM password_reset WHERE security_key = ? AND user_id = ? AND expiry_date >= ?"))
        {
            $stmt->bind_param('sis',$security_key, $user_id, $curDate);
            $stmt->execute();
            $stmt->execute();
            $stmt->store_result();
            $numRows = $stmt->num_rows();
            $stmt->bind_result($user_id);
            $stmt->fetch();
            $stmt->close();
            if ($numRows > 0 && $user_id != '')
            {
                return array('status'=>true,'user_id'=>$user_id);
            }
        }
        return false;
    }
     
    function updateUserPassword($user_id, $password, $security_key)
    {
        global $mysqli;
        if (checkEmailsecurity_key($security_key,$user_id) === false) return false;
        if ($stmt = $mysqli->prepare("UPDATE members SET password = ? WHERE id = ?"))
        {
            $password = md5(trim($password) . PW_SALT);
            $stmt->bind_param('si',$password,$user_id);
            $stmt->execute();
            $stmt->close();
            $stmt = $mysqli->prepare("DELETE FROM password_reset WHERE security_key = ?");
            $stmt->bind_param('s',$security_key);
            $stmt->execute();
        }
    }
     
    function getUserName($user_id)
    {
        global $mysqli;
        if ($stmt = $mysqli->prepare("SELECT username FROM members WHERE id = ?"))
        {
            $stmt->bind_param('i',$user_id);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($username);
            $stmt->fetch();
            $stmt->close();
        }
        return $username;
    }
    

    Password Form

    <?php
    include_once 'db_connect.php';
    include_once 'functions.php';
    include_once 'formatting.php';	
    sec_session_start();
    if (login_check($mysqli) == true) 
    	{
        $logged = 'in';
    	} 
    	
    
    
    $show = 'emailForm'; //which form step to show by default
    if ($_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))
    {
        $_SESSION['lockout'] = false;
        $_SESSION['badCount'] = 0;
    }
    if (isset($_POST['subStep']) && !isset($_GET['a']) && $_SESSION['lockout'] != true)
    {
        switch($_POST['subStep'])
        {
            case 1:
                //we just submitted an email or username for verification
                $result = checkUNEmail($_POST['username'],$_POST['email']);
                if ($result['status'] == false )
                {
                    $error = true;
                    $show = 'userNotFound';
                } else {
                    $error = false;
                    $show = 'securityForm';
                    $securityUser = $result['id'];
                }
            break;
            case 2:
                //we just submitted the security question for verification
                if ($_POST['user_id'] != "" && $_POST['security_a'] != "")
                {
                    $result = checkSecAnswer($_POST['user_id'],$_POST['security_a']);
                    if ($result == true)
                    {
                        //answer was right
                        $error = false;
                        $show = 'successPage';
                        $passwordMessage = sendPasswordEmail($_POST['user_id']);
                        $_SESSION['badCount'] = 0;
                    } else {
                        //answer was wrong
                        $error = true;
                        $show = 'securityForm';
                        $securityUser = $_POST['user_id'];
                        $_SESSION['badCount']++;
                    }
                } else {
                    $error = true;
                    $show = 'securityForm';
                }
            break;
            case 3:
                //we are submitting a new password (only for encrypted)
                if ($_POST['user_id'] == '' || $_POST['security_key'] == '') header("location: ../login.php");
                if (strcmp($_POST['pw0'],$_POST['pw1']) != 0 || trim($_POST['pw0']) == '')
                {
                    $error = true;
                    $show = 'recoverForm';
                } else {
                    $error = false;
                    $show = 'recoverSuccess';
                    updateUserPassword($_POST['user_id'],$_POST['pw0'],$_POST['security_key']);
                }
            break;
        }
    }
    
    elseif (isset($_GET['a']) && $_GET['a'] == 'recover' && $_GET['email'] != "") {
        $show = 'invalidKey';
        $result = checkEmailKey($_GET['email'],urldecode(base64_decode($_GET['u'])));
        if ($result == false)
        {
            $error = true;
            $show = 'invalidKey';
        } elseif ($result['status'] == true) {
            $error = false;
            $show = 'recoverForm';
            $securityUser = $result['user_id'];
        }
    }
    if ($_SESSION['badCount'] >= 3)
    {
        $show = 'speedLimit';
        $_SESSION['lockout'] = true;
        $_SESSION['lastTime'] = '' ? mktime() : $_SESSION['lastTime'];
    }
    ?>
    
    	 
    
    
    <!doctype html>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Password Recovery</title>
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    </head>
    <body>
    <div id="header"></div>
    <div id="page">
    
    <?php switch($show) {
        case 'emailForm': ?>
        <h2>Password Recovery</h2>
        <p>You can use this form to recover your password if you have forgotten it. Because your password is securely encrypted in our database, it is impossible actually recover your password, but we will email you a link that will enable you to reset it securely. Enter either your username or your email address below to get started.</p>
        <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
            <div class="fieldGroup"><label for="username">Username</label><div class="field"><input type="text" name="username" id="username" value="" maxlength="20"></div></div>
            <div class="fieldGroup"><label>- OR -</label></div>
            <div class="fieldGroup"><label for="email">Email</label><div class="field"><input type="text" name="email" id="email" value="" maxlength="255"></div></div>
            <input type="hidden" name="subStep" value="1" />
            <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
            <div class="clear"></div>
        </form>
        <?php break; case 'securityForm': ?>
        <h2>Password Recovery</h2>
        <p>Please answer the security question below:</p>
        <?php if ($error == true) { ?><span class="error">You must answer the security question correctly to receive your lost password.</span><?php } ?>
        <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
            <div class="fieldGroup">
    			<label>Question</label>
    				<div class="field"><?= getSecurityQuestion($securityUser); ?></div>
    		</div>
    			
            <div class="fieldGroup">
    			<label for="security_a">Answer</label>
    				<div class="field"><input type="text" name="security_a" id="security_a" value="" maxlength="255"></div>
    		</div>
            <input type="hidden" name="subStep" value="2" />
            <input type="hidden" name="user_id" value="<?= $securityUser; ?>" />
            <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
            <div class="clear"></div>
        </form>
     
         
         <?php break; case 'userNotFound': ?><br>    
    	 <h2>Password Recovery</h2><br>    
    	 <p>The username or email you entered was not found in our database.<br /><br />
    	 <a href="?">Click here</a> to try again.</p><br>    
    	 <?php break; case 'successPage': ?><br>    
    	 <h2>Password Recovery</h2><br>    
    	 <p>An email has been sent to you with instructions on how to reset your password. 
    	 <strong>(Mail will not send unless you have an smtp server running locally.)</strong>
    	 <br /><br /><a href="../login.php">Return</a> to the login page. </p><br>    
    	 <p>This is the message that would appear in the email:</p><br>    
    	 <div class="message"><?= $passwordMessage;?></div><br>    
    	
    	
    	 <?php break;
    case 'recoverForm': ?>
        <h2>Password Recovery</h2>
        <p>Welcome back, <?= getUserName($securityUser=='' ? $_POST['user_id'] : $securityUser); ?>.</p>
        <p>In the fields below, enter your new password.</p>
        <?php if ($error == true) { ?><span class="error">The new passwords must match and must not be empty.</span><?php } ?>
        <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
            <div class="fieldGroup"><label for="pw0">New Password</label><div class="field"><input type="password" class="input" name="pw0" id="pw0" value="" maxlength="20"></div></div>
            <div class="fieldGroup"><label for="pw1">Confirm Password</label><div class="field"><input type="password" class="input" name="pw1" id="pw1" value="" maxlength="20"></div></div>
            <input type="hidden" name="subStep" value="3" />
            <input type="hidden" name="user_id" value="<?= $securityUser=='' ? $_POST['user_id'] : $securityUser; ?>" />
            <input type="hidden" name="security_key" value="<?= $_GET['email']=='' ? $_POST['security_key'] : $_GET['email']; ?>" />
            <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
            <div class="clear"></div>
        </form>
        <?php break; case 'invalidsecurity_key': ?>
        <h2>Invalid security_key</h2>
        <p>The security_key that you entered was invalid. Either you did not copy the entire security_key from the email, you are trying to use the security_key after it has expired (3 days after request), or you have already used the security_key in which case it is deactivated.<br /><br /><a href="login.php">Return</a> to the login page. </p>
        <?php break; case 'recoverSuccess': ?>
        <h2>Password Reset</h2>
        <p>Congratulations! your password has been reset successfully.</p><br /><br /><a href="login.php">Return</a> to the login page. </p>
        <?php break; case 'speedLimit': ?>
        <h2>Warning</h2>
        <p>You have answered the security question wrong too many times. You will be locked out for 15 minutes, after which you can try again.</p><br /><br /><a href="login.php">Return</a> to the login page. </p>
        <?php break; }
        ob_flush();
        $mysqli->close();
    ?>
    
    
    <!--PAGE CONTENT-->
    </div>
    </body>
    </html>
    
    
    
    
  8. Hi All,

     

    I have temporarily taken over the administration of an existing site that will soon e discontinued, however I need to add a few links to files without re-inventing the wheel.

     

    The link needs to link to a file using a URL. below is the link that I have created, however it is not opening the file:

    [readon2 url="images/repairs/returns policy  process effective 1 feb 
    2014.pdf"]Returns Policy Process (Effective 1 Feb 2014)[/readon2]

    Regularly these files link to new webpages with content on them, here is a working link:

     
    [readon2 
    url="index.php?option=com_content&view=article&id=504&Itemid=504"]Repairs 
    Status[/readon2]

    but as mentioned, I need it to link directly to a file and not to a page, keeping the format of the link.

     

    Thanks

     

     

  9. Hi All,

     

    I have a form that has an attendance status field. This field needs to populate two different rows in my table. But I am not able to get my case statement to work.

     

    Here is my current code:

            // INSERT THE NEW FOR INFORMATION INTO THE DATABASE TABLE
            if ($insert_stmt = $mysqli->prepare(	"INSERT INTO 
    															shift_agent_report 
    												(			
    															shift
    												,			username
    												, 			agent
    												, 			attendance_indicator
    												, 			attendance_status
    												, 			agent_comments
    												) 
    												VALUES 
    												(
    															?
    												, 			?
    												, 			?
    												, 			(CASE 
    																	WHEN (attendance_status = 'Present') THEN '0'
    																	ELSE '1'
    															END) AS attendance_indicator
    												, 			?														
    												, 			?
    												)"))
    			
    
    		{
    	
    			$insert_stmt->bind_param('ssssss' ,$shift, $username, ucfirst($agent), $attendance_status, $attendance_status, $agent_comments);
                // EXECUTE THE PREPARED QUERY
                if (! $insert_stmt->execute())
    			//PRINT THE NUMBERS OF ROWS THAT HAVE BEEN AFFECTED 
     			{
    				//var_dump($_POST);exit;
    				header('Location: ../error.php?err=Registration failure: INSERT');
    				exit;
    
                }
    			include "../success/shift_agent_success.php";
    			exit;
            }
    
    		
    
    		/* CLOSE THE CONNECTION */
    		$mysqli->close();
        }
    
    }
    
    ?>
    
  10. Ok, I am ashamed to have to supply a solution to this, and have to say sorry for wasting time. I had originally had the column named level in both my members table and my members_info table. However, when doing some of the structural changes I removed the level column from my members_info table, but never removed it from my insert query.

     

    I slowly went throught he query and added the columns one by one, and realised this (I fee like an idiot), and now it works. The only thing I don't get is why didn't I get an error message from the server saying that the column doesn't exist or something of that sort?

     

    Thanks for your help on this though mac_gyver

  11. The mysqli works on all my other forms. And I have multiple queries running on at least two other forms. It is only the register.addinfo.php file that is only updating, but not inserting into the table.

     

    This is the code from that particular page:

    FORM

    <!doctype html>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    
    <!-- INCLUDING REQUIRED AUTHENTICATION FILES, DATABASE CONNECTIONS, FUNCTIONS. -->
    
    
    
    <?php
    include_once 'includes/db_connect.php';
    include_once 'includes/functions.php';
    include_once 'includes/formatting.php';
    
    sec_session_start();
    if (login_check($mysqli) == true) 
    	{
        $logged = 'in';
    	} 
    else 
    	{
        $logged = 'out';
    	header('location:index.php');
    	echo 'You are required to login';
    	exit;
    	}
    	
    // CHECKS IF THERE ARE ANY ERRORS WITH CONNECTING TO THE DATABASE	
    if (mysqli_connect_errno()) 
    	{
    		printf("Connect failed: %s\n", mysqli_connect_error());
    		exit();
    	}
    $error_msg = "";
    $username = $_SESSION['username'];
    $email = $_SESSION['email'];
    $level = $_SESSION['level'];
    $id = $_SESSION['user_id'];
    ?>
    
    <!--
    	Copyright 2014 TechDesignLab
    	CRM TRACKING UTILITY
    -->
    
    
    
    
    
    
    
    <!-- HEADER CONTENT OF PAGE - THIS CONTAINS ALL SCRIPT, CSS, AND META TAG RELATED INFORMATION FOR THE WEBPAGE -->
    
    <head>
      	<title>Altech Autopage - Registration</title>
    </head>
    
    
    
    
    <!-- BODY CONTENT OF THE WEBPAGE - THIS IS HOW THE PAGE WILL BE DISPLAYED TO THE USER -->
    
    <body>
    
    <!-- LOGIN / DROP DOWN PANEL START -->
    
    <!-- LEFT SECTION OF THE LOGIN PANEL IS DEFINED HERE. THE SECTION BELOW IS WHAT WILL BE SEEN BY USERS WHO ARE LOGGED IN-->
    
    
    
    <!-- INCLUDING THE NAVIGATION MENU -->
    
    
    <?php
    // INCLUDING THE TOP LOGIN / LOGOUT PANEL
    include 'includes/panel.php';
    
    // INCLUDING THE NAVIGATION MENU
    include '/nav/menu.html';
     
    ?>
    
    
    
    
    
        <div id="container">
    		<div id="content" style="margin-top:-45px;">
    		<img src="images/logo.png" alt="Altech Autopage"></img>
    			<h1>Auxilium</h1>
    			<!-- <h2>Sliding login panel with jQuery - Demo</h2>	 -->
    		
    		<div id="stylized" class="form">
    			<form id="form" name="form" method="post" action="process/register.addinfo.php">
    			<h1 style="color:red; width:600px; margin-left:90px;">Complete Registration</h1>
    			<p style="color:red; width:600px; ;">You are required to complete the remainder of the registration to continue using Auxilium.</p>
    
    			<h1 style="width:600px; margin-left:90px;">Access Details</h1>			
    			
    			<!-- DISPLAY THE DETAILS OF THE LOGGED IN USER -->
    			<label>User Logged In :
    			<span class="small">You are logged in as</span>
    			</label>
    			<input type="text" name="username" id="username" value="<?php echo htmlentities($_SESSION['username']);?>" readonly style="background-color: #C9C9C9">
    			
    			
    			<label>E-Mail :
    			<span class="small">Your Altech Autopage e-mail cannot be edited here</span>
    			</label>
    			<input type="text" name="email" id="email" value="<?php echo htmlentities($_SESSION['email']);?>" readonly style="background-color: #C9C9C9"/>
    
    			<label>ID :
    			<span class="small">ID used to identify your user in the database</span>
    			</label>
    			<input type="text" name="user_id" id="user_id" value="<?php echo htmlentities($_SESSION['user_id']);?>" readonly style="background-color: #C9C9C9"/>			
    			
    
    			<!-- FIELD FOR CAPUTRING THE CUSTOMER'S FIRST NAME -->
    			<label>First Name :
    			<span class="small">Your legal name</span>
    			</label>
    			<input type="text" name="fname" id="fname"/>
    			
    			<!-- FIELD FOR CAPUTRING THE CUSTOMER'S FIRST NAME -->
    			<label>Known As :
    			<span class="small">What do you want us to call you</span>
    			</label>
    			<input type="text" name="known_as" id="known_as"/>			
    
    			
    			<!-- FIELD FOR CAPUTRING THE CUSTOMER'S SURNAME -->
    			<label>Surname :
    			<span class="small">Your family name</span>
    			</label>
    			<input type="text" name="lname" id="lname"/>
    
    			<label>Gender :
    			<span class="small">Your gender</span>
    			</label>
    			<select id="qender" name="gender">
    				<option value=""> -- Select your gender --</option>
    				<option value="Female">Female</option>
    				<option value="Male">Male</option>
    			</select>
    			
    			
    			<label>Race :
    			<span class="small">Your racial group</span>
    			</label>
    			<select id="race" name="race">
    				<option value=""> -- Select your race --</option>
    				<option value="African">African</option>
    				<option value="Asian">Asian</option>					
    				<option value="Caucasian">Caucasian</option>
    				<option value="Coloured">Coloured</option>					
    			</select>			
    
    						<!-- FIELD FOR CAPUTRING THE CUSTOMER'S MSISDN / CONTACT NUMBER -->
    			<label>Start Date : 
    			<span class="small">Your official starting date at Altech Autopage</span>
    			</label>
    			<input id="start_date" name='start_date' type="text">	
    			
    			
    			<label>Department :
    			<span class="small">Area you work in</span>
    			</label>
    			<select id="department" name="department">
    				<option value=""> -- Select your department --</option>
    				<option value="3rd Party">3rd Party</option>
    				<option value="Cashier">Cashier</option>
    				<option value="Client Liaison Consultant">Client Liaison Consultant</option>
    				<option value="Credit Control Consultant">Credit Control Consultant</option>
    				<option value="Insurance Consultant">Insurance Consultant</option>
    				<option value="Manager">Manager</option>
    				<option value="Meeting/Interview">Meeting/Interview</option>
    				<option value="Premier Client Consultant">Premier Client Consultant</option>
    				<option value="Retail Shop Consultant">Retail Shop Consultant</option>
    				<option value="Retention Collection">Retention Collection</option>
    				<option value="Tech Deck Consultant">Tech Deck Consultant</option>
    			</select>
    			
    			
    			<label>Title :
    			<span class="small">What best describes your job role</span>
    			</label>
    			<select id="level" name="level">
    				<option value=""> -- Select your reporting level --</option>
    				<option value="5">1st Level Manager</option>
    				<option value="4">2nd Level Manager</option>
    				<option value="4">Workforce Planner</option>
    				<option value="4">Report Administrator</option>	
    				<option value="4">Team Manager</option>							
    				<option value="3">Call Centre Agent</option>												
    				<option value="3">Retail Agent</option>	
    				<option value="3">Reception Hostess</option>		
    
    			</select>			
    
    
    			<!-- FIELD FOR CAPUTRING THE CUSTOMER'S MSISDN / CONTACT NUMBER -->
    			<label>Contact Number :
    			<span class="small">Your contact number</span>
    			</label>
    			<input type="text" name="msisdn" id="msisdn"/>			
    			
    
    			<!-- FIELD FOR CAPUTRING THE CUSTOMER'S MSISDN / CONTACT NUMBER -->
    			<label>Date of Birth : 
    			<span class="small">Your birth date</span>
    			</label>
    			<input id="dob" name='dob' type="text">						
    	
    
    			<label>About Me :
    			<span class="small">Tell us a few fun facts about yourself. You may use up to a maximum of 5,000 characters.</span>
    			</label>			
    
    			<textarea name="details" rows="3"></textarea>
    	
    	
    			<!-- FIELD FOR CAPUTRING THE CUSTOMER'S MSISDN / CONTACT NUMBER -->
    			<label>Emergency Contact :
    			<span class="small">Who should we contact in an emergency?</span>
    			</label>
    			<input type="text" name="emergency_contact" id="emergency_contact" />		
    			
    			
    			<!-- FIELD FOR CAPUTRING THE CUSTOMER'S MSISDN / CONTACT NUMBER -->
    			<label>Emergency Contact Number :
    			<span class="small">What is your emergency contact's number?</span>
    			</label>
    			<input type="text" name="emergency_msisdn" id="emergency_msisdn" />				
    			
    			
    			
    			<input type="button" value="Submit" class="bt_login" onClick="form.submit()"/> 
    			</form></div>
    			
    		<br><br><br><br><br><br><br><br><br><br><br><br><br>
    		<br><br><br><br><br><br><br><br><br><br><br><br><br>
    		<br><br><br><br><br><br><br><br><br><br><br><br>
    		</div><!-- / content -->		
    	</div><!-- / container -->
    </body>
    
    
    
    <div id="container">
    <div id="footer" style="margin-top:10px;">
    
    <footer style="background:#E5E5E5; height:20px">
      <p>Copyright © Altech Autopage 2014 | <a href="mailto:lclaassen@autopage.altech.co.za">Contact Us</a>.</p>
      <img src="images/altron-footer-logo.png" alt="Altron Footer Logo" align="left"></img>
      <img src="images/altech_bbbee.png" alt="Altech Level 2 BBEE" align="left"></img>
    </footer>
    </div>	
    </div>
    </html>
    
    
    
    
    
    

    Submit File:

    <?php
    
    
    
    
    include_once '../includes/db_connect.php';
    include_once '../includes/functions.php';
    sec_session_start();
    if (login_check($mysqli) == true) 
    	{
        $logged = 'in';
    	} 
    
    $error_msg = "";
    $username = $_SESSION['username'];
    $email = $_SESSION['email'];
    $id = $_SESSION['user_id'];
    
    // create string of queries separated by ;
    	//var_dump(login_check($mysqli));
    	//var_dump($_SESSION); exit; 
    	//var_dump($_POST);exit; 
    
    
    $query  =  	"UPDATE 
    						members 
    			SET
    						level = '$_POST[level]'
    			WHERE 
    						id = $id
    			LIMIT
    						1;";
    						
    						
    $query .= 	"INSERT INTO 
    						members_info 
    			(
    						id
    			, 			fname
    			, 			known_as
    			, 			lname
    			,			gender
    			, 			race
    			,			start_date
    			, 			department
    			, 			level
    			, 			msisdn
    			, 			dob
    			, 			details
    			, 			emergency_contact
    			, 			emergency_msisdn
    			) 
    			VALUES 
    			(
    						'($_POST['user_id'])'
    			, 			'($_POST['fname'])'
    			, 			'($_POST['known_as'])'
    			, 			'($_POST['lname'])'
    			, 			'($_POST['gender'])'
    			, 			'($_POST['race'])'
    			,			'($_POST['start_date'])'
    			, 			'($_POST['department'])'
    			, 			'($_POST['level'])'
    			, 			'($_POST['msisdn'])'
    			, 			'($_POST['dob'])'
    			, 			'($_POST['details]'])'
    			, 			'($_POST['emergency_contact'])'
    			, 			'($_POST['emergency_msisdn'])'
    			);";
    
    // execute query - $result is false if the first query failed
    $result = mysqli_multi_query($mysqli, $query);
    
    if ($result) 
    {
        do {
            // grab the result of the next query
            if (($result = mysqli_store_result($mysqli)) === false && mysqli_error($mysqli) != '') {
                echo "Query failed: " . mysqli_error($mysqli);
            }
    		
    		} while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
    
    } else {
        echo "Update Query  Failed..." . mysqli_error($mysqli);
    }
    
    
    		$mysqli->close();
    
    if($failed == false) {
        header('Location: ../index.php');
        exit;
    }
    

    for now I removed the .mysqli_real_escape_string from the POST as I have not yet figured out exactly how to use this, but I am busy researching it.

     

    However I still get the fatal error message when I turn error reporting on.

  12. Yip, those two line were as follows:

    ; error_reporting = E_ALL
    
    ; display_errors = On
    

    And I then changed them to:

    error_reporting = E_ALL
    
    display_errors = On
    

    When checking the error log, I wasn't able to actually find the correct error in the logs, as the time set in my log seems to be in the incorrect zone.

     

    I will replicate the error and post any messages that I get in the error log.

  13. Ok, let me go look if I see something.

     

    When changing the php.ini file to enable editing earlier, I only uncommented the two error reporting fields, and nothing else.

     

    The error occurred when I tried to submit a file, but this was because I was already on a preloaded page. I then closed my browser completely, and was then not even able to access my index.php page. At this point it returned the same error.

  14. Do I need to install anything additional to be using this? Or is it just a matter of commenting it in the php.ini, as it is already commented in.

     

    What doesn't make sense though, is that the db_connect files uses mysqli to establish the connection to my database and this all seems to work as my other forms on my site work. Its just this particular page that for some reason only updates, but doesn't insert. I have another page that updates and inserts as well and it is working, I have even looked at duplicating that code and just changing the required fields.

     

    I installed my Apache, MySQL, and PHP using XAMP. And yes I'm running on Windows Server 2013. Not my first choice, but it is what was given to me by the company to work with.

  15. I've come across this regarding mysqli.

    If you connection string is:
    mysql_connect()
    
    then use:
    mysql_real_escape_string($_POST[''])
    
    If it is:
    $mysqli = new mysqli();
    
    then use:
    $mysqli->real_escape_string($_POST[''])
    
    

    So with that in mind, does it suggest that my script should actually be:

    <?php
    
    include_once '../includes/db_connect.php';
    include_once '../includes/functions.php';
    sec_session_start();
    if (login_check($mysqli) == true) 
    	{
        $logged = 'in';
    	} 
    
    $error_msg = "";
    $username = $_SESSION['username'];
    $email = $_SESSION['email'];
    $id = $_SESSION['user_id'];
    
    // create string of queries separated by ;
    	//var_dump(login_check($mysqli));
    	//var_dump($_SESSION); exit; 
    	//var_dump($_POST);exit; 
    
    
    $query  =  	"UPDATE 
    						members 
    			SET
    						level = '$_POST[level]'
    			WHERE 
    						id = $id
    			LIMIT
    						1;";
    						
    						
    $query .= 	"INSERT INTO 
    						members_info 
    			(
    						id
    			, 			fname
    			, 			known_as
    			, 			lname
    			,			gender
    			, 			race
    			,			start_date
    			, 			department
    			, 			level
    			, 			msisdn
    			, 			dob
    			, 			details
    			, 			emergency_contact
    			, 			emergency_msisdn
    			) 
    			VALUES 
    			(
    
    						$mysqli->real_escape_string($_POST['user_id'])
    			, 			$mysqli->real_escape_string($_POST['fname'])
    			, 			$mysqli->real_escape_string($_POST['known_as'])
    			, 			$mysqli->real_escape_string($_POST['lname'])
    			, 			$mysqli->real_escape_string($_POST['gender'])
    			, 			$mysqli->real_escape_string($_POST['race'])
    			,			$mysqli->real_escape_string($_POST['start_date'])
    			, 			$mysqli->real_escape_string($_POST['department'])
    			, 			$mysqli->real_escape_string($_POST['level'])
    			, 			$mysqli->real_escape_string($_POST['msisdn'])
    			, 			$mysqli->real_escape_string($_POST['dob'])
    			, 			$mysqli->real_escape_string($_POST['details]'])
    			, 			$mysqli->real_escape_string($_POST['emergency_contact'])
    			, 			$mysqli->real_escape_string($_POST['emergency_msisdn'])
    			);";
    
    // execute query - $result is false if the first query failed
    $result = mysqli_multi_query($mysqli, $query);
    
    if ($result) 
    {
        do {
            // grab the result of the next query
            if (($result = mysqli_store_result($mysqli)) === false && mysqli_error($mysqli) != '') {
                echo "Query failed: " . mysqli_error($mysqli);
            }
    		
    		} while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
    
    } else {
        echo "Update Query  Failed..." . mysqli_error($mysqli);
    }
    
    
    		$mysqli->close();
    
    if($failed == false) {
        header('Location: ../index.php');
        exit;
    }
    
    
    
  16. in programming, you cannot assume anything. the parameters of the mysqli function calls are different from mysql. a way to avoid the confusion between mysql and msyqli is to use the object notation for mysqli (which actually results in shorter syntax.)

     

    i'm not sure why you had any mysql functions in your code. weren't you using mysqli all along in these series of threads?

     

     

    Yes I am using mysqli, but I didn't have *_real_escape_string preceeding my $_POST at all. The suggestion given to me was to add it as I did in my code, the only difference was is was mysql_real_escape_string and not the mysqli_real_escape_string as I had put it.

     

    This is the thread where the suggestion was made:

    http://forums.phpfreaks.com/topic/285759-where-to-put-redirect-header/ 

  17. Here is the output I get when enabling the error reporting in php.ini.

    Fatal error: Class 'mysqli' not found in C:\htdocs\includes\db_connect.php on line 4
    

     And this is db_connect.php and psl-config.php

    db_connect.php
    <?php
    //includes/db_connect.php 
    include_once 'psl-config.php';   // As functions.php is not included
    $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
    
    ?>
    
    
    psl-config.php
    <?php
    // includes/psl-config.php -->
    
    /**
    * These are the database login details
    */  
    define("HOST", "localhost");     // The host you want to connect to.
    define("USER", "username");    // The database username. 
    define("PASSWORD", "mypassword");    // The database password. 
    define("DATABASE", "mydatababse");    // The database name.
    define("CAN_REGISTER", "any");
    define("DEFAULT_ROLE", "member");
    
    define("SECURE", FALSE);    // FOR DEVELOPMENT ONLY!!!!
    
    // Root Administration    define("ADMINISTRATION", "system"); -->
    // The test user password define("TESTUSER","test"); -->
    
    ?>
    
×
×
  • 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.