-2

I am building a login form in a HTML page login.html. Now after submitting the form the data is send to a php server side script named login.php. My problem is that if for some error say if the username is already present in the database table I want the user to stay in the same page with a red colored warning. Or if I want to add the popular two passwords did not match error message. How can I achieve this. As the data is stored in a mysql database I cannot access it using any client side script. But in my approach the php script moves the user to another page. And there is no way to dynamically make some error messages visible. I tried to make seperate html pages for this purpose, but I think it is not a very good solution. Can anyone provide me a sample code for this purpose? Thanks in advance.

1 Answers1

0

You can either change messages with a switch statement in login.php (login.php would display the error message), or you can send the user back to login.html with an error code appended to url that can be retrieved (that is what I would do).

Using Switch in login.php

You would enter your predefined error code into an error function, there are multiple ways to do this.

function display_error_message($e) {
    switch ($e) {
        case "error_1":
            echo "Error message 1";
            break;
        case "error_2":
            echo "Error message 2";
            break;
        //Will execute the default if the error code does not match
        default:
            echo "Error message 2";
    }
}

Calling:

display_error_message("error_1");

Appending Error to URL of login.html (recommended)

Here we again use a function. It will redirect user back to login.html with the error, this can be used on a successful login as well with append /?status=success.

Please note that you cannot use the header() function if any content is being displayed on login.php before the function is executed.

function error_redirect($e) {
    header("Location: www.example.com/login.html?error=$e");
    exit();
}

Calling:

error_redirect("nouser");