Hi All

See the code give given below. I was fighting with this code since last 5 hours to know why isset() is eveluating the condition as false if value is posted exactly what it shall POST.
If I uncomment the line no. - 4,5,6,7,8 and put rest of the code from line no. 10 to 28 I can see the POSTED value .
Can Anyone help in this by any guidance or suggestion. I will be thankful.

<?php
include 'dbconnection.php';
include 'functions.php';
//sec_session_start();
 //  $email = $_POST['logemail'];
 //  $password = $_POST['p'];
//  echo $password;
//  echo $email;
 // Our custom secure way of starting a php session. 

if(isset($_POST['logemail'], $_POST['p'])) { 
   $email = $_POST['logemail'];
   $password = $_POST['p']; // The hashed password.
   if(login($email, $password, $mysqli) === true) {
      // Login success
      //$url = 'mwq';
    //echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';  
    echo $password;
    echo $email;

   } else {
      // Login failed
      header('Location: login.php?error=1');
   }
} else { 
   // The correct POST variables were not sent to this page.
   echo 'Invalid Request Data Not POSTED';
}
?>

Try changing Line 14 to :

if(isset($_POST['logemail'] && $_POST['p'])) { 

Where is the login() function and $mysqli variable coming from?

Hi Squidge
I tried your code it is giving error I made simple change in your code -
Your code - if(isset($_POST['logemail'] && $_POST['p']))
My code - if(isset($_POST['logemail']) && isset($_POST['p'])) //this is not giving error

I also added echo var_dump($_POST); //just before isset line and gout output - array(0) { }

Both the data is coming from -

<FORM ID="Login" ACTION="login.php" METHOD="POST">
    <h1>welcome to the login page</h1>
    please input the login details to create an account here<br />
    <table border="2">
    <tr>
    <td>email :</td><td><input id="logemail" name="logemail" type="text" size"30"></input></td>
    </tr>
    <tr>
    <td>password :</td><td><input id="logpass1" name="logpass1" type="password" size"20"></input></td>
    </tr>
    </table>
    <input type="button" value="Login" onClick="formhash2(this.form,this.form.logpass1);">
    </FORM>

But interesting part of the code is if I remove the comment from these

// $email = $_POST['logemail'];
// $password = $_POST['p'];
// echo $password;
// echo $email;

and rest of the code I commented then I get waht I expect from POST.

But that doesnt explain where the login() function is coming from. Can you comment out the login function and echo the data. I think the error is the login(). Plus u havent answered where the $mysqli variable is coming from

Member Avatar for LastMitch

@vishalonne

Your code:

if(login($email, $password, $mysqli) === true)

should look like this:

if(login($email, $password, $mysqli) == true)

Please see the code for formhas2() and formhash1() -

// JavaScript Document csnip
function formhash2(form,password) {
     // Create a new element input, this will be out hashed password field.
   alert(form.id + " " + password.value);
   var p = document.createElement("input");
       // Add the new element to our form.

   p.name = "p";
   p.type = "hidden"
   p.value = hex_sha512(password.value);
   // Make sure the plaintext password doesn't get sent.
   password.value = "";
   // Finally submit the form.
   form.appendChild(p);
   form.submit();
}

function formhash1(form,password) {
    alert(form.id + " " + password.value);
  // Create a new element input, this will be out hashed password field.
  var pl = document.createElement("input");
  // Add the new element to our form.

   pl.name = "pl";
   pl.type = "hidden"
   pl.value = hex_sha512(password.value);
   // Make sure the plaintext password doesn't get sent.
   password.value = "";
   // Finally submit the form.
   form.appendChild(pl);
   form.submit();

}

and this is the login() -

function login($email, $password, $mysqli) {
   // Using prepared Statements means that SQL injection is not possible. 
   if ($stmt = $mysqli->prepare("SELECT id, email, password, salt FROM members WHERE email = ? LIMIT 1")) { 
      $stmt->bind_param('s', $email); // Bind "$email" to parameter.
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
      printf("%s %s\n", $username, $db_password);
      $stmt->fetch();
      $password = hash('sha512', $password.$salt); // hash the password with the unique 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 {
         if($db_password == $password) { // Check if the password in the database matches the password the user submitted. 
            // Password is correct!

               $ip_address = $_SERVER['REMOTE_ADDR']; // Get the IP address of the user. 
               $user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.

               $user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
               $_SESSION['user_id'] = $user_id; 
               $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
               $_SESSION['username'] = $username;
               $_SESSION['login_string'] = hash('sha512', $password.$ip_address.$user_browser);
               // 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;
      }
   }
}

Yes Yes

Member Avatar for LastMitch

@vishalonne

Yes Yes

My question is what did you do wrong? All you need to do is just copy and paste the code in the correct file and name it exactly what's on the website. If you a gonna to modify it then what changes you made since than?

Can you tell me how you name each file and the changes?

@LastMitch
index.php

<td>
<FORM ID="Login" ACTION="login.php" METHOD="POST">
<h1>welcome to the login page</h1>
please input the login details to create an account here<br />
<table border="2">
<tr>
<td>email :</td><td><input id="logemail" name="logemail" type="text" size"30"></input></td>
</tr>
<tr>
<td>password :</td><td><input id="logpass1" name="logpass1" type="password" size"20"></input></td>
</tr>
</table>
<input type="button" value="Login" onClick="formhash2(this.form,this.form.logpass1);">
</FORM>

<FORM ID="Register" ACTION="register.php" METHOD="POST">
<h1>welcome to the registration page</h1>
please input the registration details to create an account here<br />
<table border="2">
<tr>
<td>email :</td><td><input name="regemail" type="text" size"30"></input></td>
</tr>
<tr>
<td>password :</td><td><input id="regpass1" name="regpass1" type="password" size"20"></input></td>
</tr>
</table>
<input type="button" value="Register" onClick="formhash1(this.form,this.form.regpass1);">
</FORM>
</td>

process_login ----> login.php

<?php
include 'dbconnection.php';
include 'functions.php';
//sec_session_start();
 //  $email = $_POST['logemail'];
 //  $password = $_POST['p'];
//  echo $password;
//  echo $email;
 // Our custom secure way of starting a php session. 
echo var_dump($_POST);
print_r($_REQUEST);
//if(isset($_POST['logemail'] && $_POST['p'])) 
if(isset($_POST['logemail']) && isset($_POST['p'])) 
{ 
   $email = $_POST['logemail'];
   $password = $_POST['p']; // The hashed password.
   if(login($email, $password, $mysqli) === true) {
      // Login success
      //$url = 'mwq';
    //echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';  
    echo $password;
    echo $email;

   } else {
      // Login failed
      header('Location: login.php?error=1');
   }
} else { 
   // The correct POST variables were not sent to this page.
   echo 'Invalid Request Data Not POSTED';
}
?>

register.php

<?php
 include 'dbconnection.php';
 include 'functions.php';
if($_POST["regemail"] && $_POST["p"] )
{

    $email=$_POST["regemail"];
    $password=$_POST["p"];

        if(register_password($email, $password, $mysqli)===true)
        {
            print "<h1>you have registered sucessfully</h1>";
            print "<a href='index.php'>go to login page</a>";
        }
        else print "problem";
}
else print"invaild input data";
?>

forms.php ----> checkforms.php

// JavaScript Document csnip
function formhash2(form,password) {
     // Create a new element input, this will be out hashed password field.
   alert(form.id + " " + password.value);
   var p = document.createElement("input");
       // Add the new element to our form.

   p.name = "p";
   p.type = "hidden"
   p.value = hex_sha512(password.value);
   // Make sure the plaintext password doesn't get sent.
   password.value = "";
   // Finally submit the form.
   form.appendChild(p);
   form.submit();
}

function formhash1(form,password) {
    alert(form.id + " " + password.value);
  // Create a new element input, this will be out hashed password field.
  var pl = document.createElement("input");
  // Add the new element to our form.

   pl.name = "pl";
   pl.type = "hidden"
   pl.value = hex_sha512(password.value);
   // Make sure the plaintext password doesn't get sent.
   password.value = "";
   // Finally submit the form.
   form.appendChild(pl);
   form.submit();
}

functions.php ----> functions.php (added 1 functionregister_password) and changed the variable names whee ever required.

<?php
//Secure Session Start Function:Securely start a PHP session.

function sec_session_start() {
        $session_name = 'sec_session_id'; // Set a custom session name
        $secure = false; // Set to true if using https.
        $httponly = true; // This stops javascript being able to access the session id. 

        ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies. 
        $cookieParams = session_get_cookie_params(); // Gets current cookies params.
        session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly); 
        session_name($session_name); // Sets the session name to the one set above.
        session_start(); // Start the php session
        session_regenerate_id(true); // regenerated the session, delete the old one.     
}

// registertion with salted password
function register_password($email, $password, $mysqli)
{
    // The hashed password from the form
    $password = $_POST['pl']; 
    // Create a random salt
    $random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
    // Create salted password (Careful not to over season)
    //$password = hash('sha512', $password.$random_salt);

    // Add your insert to database script here. 
    // Make sure you use prepared statements!
    if ($insert_stmt = $mysqli->prepare("INSERT INTO customer (email, pass, salt) VALUES (?, ?, ?)")) 
        {
            $insert_stmt->bind_param('sss',$email, $password, $random_salt);
            // Execute the prepared query.
            $insert_stmt->execute();
            return true;
        }
}

//Secure Login Function:
function login($email, $password, $mysqli) {
   // Using prepared Statements means that SQL injection is not possible. 
   if ($stmt = $mysqli->prepare("SELECT id, email, password, salt FROM members WHERE email = ? LIMIT 1")) { 
      $stmt->bind_param('s', $email); // Bind "$email" to parameter.
      $stmt->execute(); // Execute the prepared query.
      $stmt->store_result();
      $stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
      printf("%s %s\n", $username, $db_password);
      $stmt->fetch();
      $password = hash('sha512', $password.$salt); // hash the password with the unique 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 {
         if($db_password == $password) { // Check if the password in the database matches the password the user submitted. 
            // Password is correct!

               $ip_address = $_SERVER['REMOTE_ADDR']; // Get the IP address of the user. 
               $user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.

               $user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
               $_SESSION['user_id'] = $user_id; 
               $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
               $_SESSION['username'] = $username;
               $_SESSION['login_string'] = hash('sha512', $password.$ip_address.$user_browser);
               // 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;
      }
   }
}......
Member Avatar for LastMitch

@vishalonne

I'm not going to read all of the code!

1) I just to know the name of the file.
2) I just need to know what changes.
3) That's all I need to know.

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.