0

Okay, so here's my code

<?php
$cn = new mysqli ("localhost", "root", "root", "dbsam");
$username = isset ($_POST['username']) ? $_POST['username']:"";
$password = isset ($_POST['password']) ? $_POST['password']:"";
$sql = "SELECT * FROM tbluser WHERE username=? AND password=?";
$upass = hash("SHA256", $password);
$qry = $cn->prepare($sql);
$qry->bind_param("ss", $username, $upass);
$qry->execute();
$qry->fetch();
if ($qry->num_rows()==1) {
    echo "Logged in!";
}
else {
    echo "<script>alert('Account did not match the database records!')</script>>";
    header ("location: login.php");
}
?>

If the username and password did not match, an alert box will appear. So the problem is that it doesn't appear anymore it only executes the header that I put under it but if I remove the header, the alert dialog box will appear. I want the alert box to appear then the user will be redirected to the log-in page after that. How can I do that? Great Thanks!

kboul
  • 13,836
  • 5
  • 42
  • 53
derf
  • 1
  • 1
  • You'll need to use Javascript to do the redirect if you want the alert to appear, see something like this: https://stackoverflow.com/a/506004/7956549 – stevenkellow Jul 06 '17 at 14:40
  • Might be better to show a content block (div) for a few seconds, such as a flash message, then after a few seconds redirect the user. – Adam Jul 06 '17 at 14:40
  • 1
    It may be best to set this script as a separate ajax call and return a well-structured JSON response. Then handle the response in JS. – Rob W Jul 06 '17 at 14:41

2 Answers2

2

You can set document.location, inside a script tag. Something like

<script> document.location = 'login.php'; </script>

Beside the answer to the direct question, I feel like you will need a timeout, or something more complex to handle the time spent reading the alert.

Carlo
  • 2,103
  • 21
  • 29
1

It is impossible in such way, PHP will redirect and never let the browwer executing the JS.

You can add a variable in the url then make your test in login.php then show the alert

    .....
    else {
        header ("location: login.php?mode=login_failed");
    }

    //login.php
    $mode = filter_input(INPUT_GET, 'mode');
    if ($mode === 'login_failed') {
         echo '<script>.......';
    }
Seif.ben
  • 62
  • 1
  • 4