Member Avatar for sundeep.gurroby

hello,i have no idea where i will put the passwod_verify function and what i must code the verify exactly in order to get the plain txt password be compared with the hashed version ?

my code is below and part of my database also.

<?php require_once('Connections/bankusers.php'); ?>
<?php session_start(); ?>
<?php

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  session_start();
}

$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['UserName'])) {
  $loginUsername=$_POST['UserName'];
  $password=$_POST['Password:'];
  $MM_fldUserAuthorization = "";
  $MM_redirectLoginSuccess = "loginusermemo.php";
  $MM_redirectLoginFailed = "loginuser.php";
  $MM_redirecttoReferrer = false;
  mysql_select_db($database_bankusers, $bankusers);

  $LoginRS__query=sprintf("SELECT UserID, Password FROM users WHERE UserID=%s AND Password=%s",
    GetSQLValueString($loginUsername, "int"), GetSQLValueString($password, "text")); 

  $LoginRS = mysql_query($LoginRS__query, $bankusers) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {
     $loginStrGroup = "";

    if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;       

    if (isset($_SESSION['PrevUrl']) && false) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];  
    }
    header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>
<!DOCTYPE HTML>
<html>

<head>
  <title>Login User</title>
  <meta name="description" content="website description" />
  <meta name="keywords" content="website keywords, website keywords" />
  <meta http-equiv="content-type" content="text/html; charset=windows-1252" />
  <link rel="stylesheet" type="text/css" href="style/style.css" title="style" />
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css">
</head>

<body>
<div id="main">
    <div id="header">
      <div id="logo">
        <div id="logo_text">
          <!-- class="logo_colour", allows you to change the colour of the text -->
          <h1><a href="index.php">ModelOnline<span class="logo_colour">Bank</span></a></h1>
          <h2>Your. Bank. On. Demand.</h2>
        </div>
      </div>
      <div id="menubar">
        <ul id="menu">
          <!-- put class="selected" in the li tag for the selected page - to highlight which page you're on -->
          <li class="selected"><a href="index.php">Home</a></li>
          <li><a href="register.php">REGISTER</a></li>
          <li><a href="login.php">lOGIN</a></li>
          <li><a href="aboutus.php">ABOUT US</a></li>
          <li><a href="contactus.php">Contact Us</a></li>
          <li><a href="accessibility.php">Accessibility</a></li>
          <li><a href="security.php">Security</a></li>
        </ul>
      </div>
    </div> <div align="center" class="bankservices"><a href="http://www.modelonlinebank.com/bankproducts.php#one">Current Accounts</a> | <a href="http://www.modelonlinebank.com/bankproducts.php#two">Savings Accounts</a> | <a href="http://www.modelonlinebank.com/bankproducts.php#three">Mortgages</a> | <a href="http://www.modelonlinebank.com/bankproducts.php#four">Insurance</a> | <a href="http://www.modelonlinebank.com/bankproducts.php#five">Credit Cards</a> | <a href="http://www.modelonlinebank.com/bankproducts.php#six">Investments</a></div>
    <div id="site_content">
      <div class="sidebar">
        <!-- insert your sidebar items here -->
        <h3>Latest News</h3>
        <h4>Personal Banking</h4>
        <h5>January 1st, 2014</h5>
        <p>Current Accounts,Saving Accounts,Range of Credit And Debit cards to suit all your needs. We have your interest in mind.<br />
        <a href="#">Read more</a></p>
<p></p>
        <h4>Corporate Banking</h4>
        <h5>February 5th, 2014</h5>
        <p>We help you achieve your goals by providing numerous funding options.Provide Risk management of your finances and look for strategic and finance options to promote business.<br /><a href="#">Read more</a></p>
        <h3>Useful Links</h3>
        <ul>
          <li><a href="#">Credit card</a></li>
          <li><a href="#">Debit card</a></li>
          <li><a href="#">Loans</a></li>
          <li><a href="#">Insurance</a></li>
        </ul>
        <h3>Search</h3>
        <form method="post" action="#" id="search_form">
          <p>
            <input class="search" type="text" name="search_field" value="Enter keywords....." />
            <input name="search" type="image" style="border: 0; margin: 0 0 -9px 5px;" src="style/search.png" alt="Search" title="Search" />
          </p>
        </form>
      </div>
      <div id="content">
        <!-- insert the page content here -->
        <h1>Login Part 1 of 2</h1>
        <p>Please kindly Input your Account Number and Password below:</p>
        <form action="<?php echo $loginFormAction; ?>" method="POST" name="loginform" id="loginform">
          <table width="500" border="0">
            <tr>
              <td><span id="sprytextfield1">
              <label for="UserName"></label>
              Account Number: <br>
                <input type="text" name="UserName" id="UserName">
              <span class="textfieldRequiredMsg">Enter Your Account Number.</span></span></td>
            </tr>
            <tr>
              <td><span id="sprytextfield2">
                <label for="Password:"></label>
Password: <br>
                <input type="password" name="Password:" id="Password:">
              <span class="textfieldRequiredMsg">Enter Your Password.</span></span></td>
            </tr>
            <tr>
              <td><input type="submit" name="LoginButton" id="LoginButton" value="Login"></td>
            </tr>
          </table>
        </form>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
</div>
    </div>
    <div id="content_footer"></div>
    <div id="footer">
      &copy;Modelonlinebank 2014 | <a href="#sitemap">SiteMaP</a> | <a href="#privacy">Privacy</a> | <a href="#jobs">Jobs</a> | <a href="#terms">Terms</a> | <a href="contactus.php">Feedback</a></div>
  </div>
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1");
var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2");
</script>
</body>
</html>

Once you hash a password, it cannot be undon. Therefore, you cannot cross check a text password with a hashed one. If this was possible, no password woule be safe on the web.

Here is something you might wanna try.

/**
* Check for correct password
*
* @param string $password The password in plain text
* @param string $hash The stored password hash
*
* @return bool Returns true if the password is correct, false if not.
*/
function check_hash($password, $hash)
{
    if (strlen($password) > 4096)
    {
        // If the password is too huge, we will simply reject it
        // and not let the server try to hash it.
        return false;
    }

    $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    if (strlen($hash) == 34)
    {
        return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
    }

    return (md5($password) === $hash) ? true : false;
}

password_hash for PHP version 5.5.x can verify the password from the user's input.

for example, we have user submitted form data

$password = $_POST['password'];
$username = $_POST['username'];
## don't forget to sanitize everything.

$your_query = "select username, password from USER_TABLE WHERE username = '".$username."'";

## execute your query  here and fetch the result



## and let hashed_pass equal to the row password

$hashed_pass = $row['password'];

## verify the password

if(password_verify($password, $hashed_pass)){

    ## password is valid

    }

    else{

        ## password is not valid

        }

The most important is that the $password from the user's input is not being included in the database query. The verification is occuring in the password_hash function and not in the database query itself.

Member Avatar for sundeep.gurroby

Thanks Veedeoo, u r the only one who understood my problem.
i need to break the problem into 2 parts.
1) fetch the hashedpassword from my database after username is checked.
2) compare this with the user input password to verify and allow the user to login.

Exactly, you don't fetch the password from the database using the user's password input. Only the user's inputted username.

Example: Make sure to use PDO or Mysqli. In this example, I will use shorthand PDO. Please make sure to follow the long form PDO connector suggested in PHP.net website

$username =  trim(filter_var($_POST['user_name'],FILTER_SANITIZE_STRING));
$password = trim(filter_var($_POST['user_name'],FILTER_SANITIZE_STRING));

## check the existence of the user in your database

$this_db =  new PDO('mysql:dbname=db_name;host=db_host', 'db_user', 'db_pass');

$this_stmt = $this_db->prepare("select  UserID, Username, Password FROM users WHERE Username = :username");

$this_stmt->execute(array(':username' => $username));
$res = $this_stmt->fetch();

## validate the password given by user

if(password_verify($password, $res['password'])){

        ## password is valid
        ## you can set the session here for logged_in and username
        ## $_SESSION['logged_in'] = true;
        ## $_SESSION['username'] = $res['Username'];
}
else{

       ## password is not valid, you can redirect to login page again.

}

don't forget to put session_start()....

Member Avatar for sundeep.gurroby

Thanks I was able to this from a good teacher here Click Here. But i am still using old school mysql instead of mysqli or PDO. In future projects i will surely adapt to them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.