Php – How to show error messages in HTML page in PHP

htmlPHP

I have following login form (login.php) in which I am asking for username and password.

<form action="processlogin.php" method="post">            
  <input type="text" name="username">
  <input type="password" name="password">
  <input type="submit" value="Login">                                
</form>

Following is the code snippet from my processlogin.php file

if(!$_POST["username"] || !$_POST["password"])
{
    $msg = "You left one or more of the required fields.";
    echo $msg;
    //header("Location:http://localhost/login.php");
}

This code checks whether all the mandatory fields are filled on not. If not, it shows the error message.

Till now everything is fine.

My problem is that, error message is shown in plain white page. I want to show it above the login form in login.php file. How should I change my code to get
my functionality.

Best Answer

I would prefer Jquery Validation or Ajax based Authentication. But still you can do it this way:

Put your Error Message in Session like this :

$_SESSION['Error'] = "You left one or more of the required fields.";

Than simple show it like this:

if( isset($_SESSION['Error']) )
{
        echo $_SESSION['Error'];

        unset($_SESSION['Error']);

}

In this case you can assign multiple messages in different Operations.