I want to show an error to my login page if username & password doesn't match considering my action form redirects to another php file.

tried setting $_SESSION and echoed it to my login page, the echo keeps coming back after refreshing.

login page:

<form action="test.php" method="post">

        <label>Username: </label>
        <input type="text" name="username">
        <br>
        <label>Password: </label>
        <input type="text" name="password">
        <br>
        <input type="submit" value="Register" name="submit">
        <label><?php echo $_SESSION['valid']; ?></label>
</form>

test.php:

session_start();

$uname = "user";
$pass = "123";

if(isset($_POST['submit'])) {



    $username = $_POST['username'];
    $password = $_POST['password'];

    if(($username == $uname) && ($password == $pass)) {
        $_SESSION['valid'] = "success";
        header('Location: success.php');
    } else {
        $_SESSION['valid'] = "fail";
        header('Location: index.php');
    }

i expect "Username or password is incorrect" below the submit button form.

2 Answers

0
Swati On

You can check if session is set or not in your login page like below :

<form action="test.php" method="post">

        <label>Username: </label>
        <input type="text" name="username">
        <br>
        <label>Password: </label>
        <input type="text" name="password">
        <br>
        <input type="submit" value="Register" name="submit">
        <label><?php 
       ///checking if session is set then print 
         if($_SESSION['valid']!=null && isset($_SESSION['valid'])){
            echo $_SESSION['valid']; 
         }
        ?></label>
</form>
0
Bastien Antoine On

Be careful, you have to put session_start() at the first line of every file where you want to use the session, even HTML pages. Maybe you haven't included in your login page ? See here if you want to understand why.