Home > Net >  generating a random number and send to the header
generating a random number and send to the header

Time:01-02

In my login form, if email or password is wrong I set header ('Location: login.php?Err=284613');. Then using Javascript I capture it and give the error code to the page using if (window.location.search == "?Err=284613"){}.

The issue is that I don't want the user to type login.php?Err=284613 and trigger the error code manually.

Can I generate random numbers with PHP and show different numbers each time in login.php?Err="random numbers". Of course, then I need to capture that random number with javascript in order to show the error on the page.

<?php
if (!isset($_POST['username'], $_POST['password']))
{
    exit('Please fill both the username and password fields!');
}

if ($stmt = $con->prepare('SELECT id, Password FROM users WHERE Email = ?'))
{
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();

    $stmt->store_result();
    if ($stmt->num_rows > 0)
    {
        $stmt->bind_result($id, $password);
        $stmt->fetch();
        if (password_verify($_POST['password'], $password))
        {

            session_regenerate_id();
            $_SESSION['loggedin'] = true;
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['id'] = $id;
            header('Location: index.php');

        }
        else
        {

            header('Location: login.php?Err=284613');

        }
    }
    else
    {

        header('Location: login.php?Err=284613');

    }

    $stmt->close();
}
}

?>

    
if(window.location.search == "?Err=284613")
{
    
 setError(email, 'Wrong Password!');
    
}

CodePudding user response:

Consider the following HTML / jQuery code.

$(function() {
  $(".login").submit(function(event) {
    var user = $(".login #username").val();
    var pass = $(".login #password").val();
    var valid = (user !== "") && (pass !== "");
    if (valid) {
      $.post($(this).attr("action"), {
        username: user,
        password: pass
      }, function(results) {
        if (results.error == false) {
          window.location.href = "index.php";
        } else {
          alert(results.message);
          return false;
        }
      });
    } else {
      alert("Login and Password must be entered.");
      return false;
    }
  });
})
.login ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

.login ul li label {
  display: inline-block;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form  action="login.php" method="post">
  <ul>
    <li>
      <label for="username">Login:</label>
      <input type="text" id="username" value="[email protected]" />
    </li>
    <li>
      <label for="password">Password:</label>
      <input type="password" id="password" value="Peaches!nAcan" />
    </li>
  </ul>
  <button  type="submit">Login</button>
</form>

This is an example of a very basic Login form and very basic validation. When the Form is submitted, either by button click or the User hitting Enter, an AJAX Post is sent to PHP with the Username and Password.

In your PHP, login.php, file, you might have something like:

<?php
$results['error'] = False;
header('Content-type: application/json');
if (!isset($_POST['username'], $_POST['password'])) {
  $results['error'] = True;
  $results['message'] = 'Please fill both the username and password fields!';
  echo json_encode($results);
  exit(0);
}
// Prepare connection to SQL for Select Query
if ($stmt = $con->prepare('SELECT id, Password FROM users WHERE Email = ?')) {
  $stmt->bind_param('s', $_POST['username']);
  $stmt->execute();
  $stmt->store_result();
  if ($stmt->num_rows > 0) {
    $stmt->bind_result($id, $password);
    $stmt->fetch();
    if (password_verify($_POST['password'], $password)) {
      session_regenerate_id();
      $_SESSION['loggedin'] = true;
      $_SESSION['name'] = $_POST['username'];
      $_SESSION['id'] = $id;
      echo json_encode($results);
    } else {
      $results['error'] = True;
      $results['message'] = "Incorrect Login or Password.";
      echo json_encode($results);
    }
    $stmt->close();
    exit(0);
  }
}
?>

It may seem redundant to check everything again, yet if a bad actor tries to bypass your Login Script or navigates directly to the page; they will encounter an error (in JSON). Also this assumes that index.php is looking for a valid Session.

Also if there is an error in SQL you can relay this back to the AJAX too. Something like "There was a lookup failure, please try again." Basically, this is a small script that returns some JSON data, so it is now more like an API. You Post data to it, and it gives you a JSON response. This makes AJAX requests very easy.

When the data is posted, if there is no Error, the initial False is returned to the AJAX Request and the script handles this by redirecting the browser to the new page. If it is changed to True, the message is passed back to the AJAX request and it displays the message.

See More:

  • Related