'How to display login error and "fill all the fields" messages on the same page using php?
I am building a php login page where the user is required to put in a username and password for logging in.
My question is
- how can I display the 'invalid username or password' error message on the same page?
- how can I display the "Fill up all the fields" message when users leave the fields empty?
In the code below when I leave the fields empty the "fill up all the fields" message disappears quickly. When I type a wrong password or username same thing happens. How can I get those messages to stay on shown on the page when an error occur?
Code:
<?php
session_start();
$json = isset($_POST["admin"]) ? $_POST["admin"] : "";
if (!($admin = checkJson($json))) {
print "Fill up all the fields";
exit();
}
mysqli_report(MYSQLI_REPORT_ALL ^ MYSQLI_REPORT_INDEX);
try {
$initials = parse_ini_file("../.ht.asetukset.ini");
$connection = mysqli_connect($initials["databaseserver"], $initials["username"], $initials["password"], $initials["database"]);
} catch (Exception $e) {
header("Location:../html/connectionError.html");
exit();
}
// Tehdään sql-lause, jossa kysymysmerkeillä osoitetaan paikat
// joihin laitetaan muuttujien arvoja
$sql = "select * from admin where uname=? and paswd=SHA2(?, 256)";
try {
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $admin->uname, $admin->paswd);
mysqli_stmt_execute($stmt);
$print = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_object($print)) {
$_SESSION["admin"] = "$row->uname";
print $_SESSION["returnSite"];
exit();
} else
print "Invalid username or password!";
mysqli_close($connection);
print "Login in...";
} catch (Exception $e) {
print "Error!";
}
?>
<?php
function checkJson($json)
{
if (empty($json)) {
return false;
}
$admin = json_decode($json, false);
if (empty($admin->uname) || empty($admin->paswd)
) {
return false;
}
return $admin;
}
?>
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="">
<meta name="description"
content="Team 14 project work. The website contains basic web development guides utilizing HTML5, CSS, JavaScript and Bootstrap">
<title>admin login</title>
<!--Link to bootstrap.-->
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous">
<!--Link to local css file.-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Dosis&display=swap"
rel="stylesheet">
</head>
<body>
<header>
<!--navigation bar starts here.-->
<nav class="navbar navbar-expand-lg navbar-light">
<div class="container-fluid">
<a class="navbar-brand" href="../html/index.html"
style="color: #0000ff; font-family: 'Dosis', sans-serif; font-size: 20px;"><b>CodeSchool</b></a>
<div id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link active"
aria-current="page" href="../html/html.html">HTML Basics</a></li>
<li class="nav-item"><a class="nav-link active"
href="../html/css.html">CSS Basics</a></li>
<li class="nav-item"><a class="nav-link active"
href="../html/js.html">JavaScript</a></li>
<li class="nav-item">
<!--anchor link added.--> <a class="nav-link active" href="#a">About
Us</a>
</li>
<li class="nav-item">
<!--anchor link added.--> <a class="nav-link active" href="#b">Contact
Us</a>
</li>
<li class="nav-item">
<!--anchor link added.--> <a class="nav-link active" href="../html/login.html">Log
In / Sign Up</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<!--navigation bar ends here.-->
<main>
<div class="box" style="background-color: #2f303a; color:white">
<h1 class="padding"><b>Admin login Page</b></h1><br>
<h1 class="padding"><b>Please provide your Administrator login credentials</b></h1><br>
</div>
<!--box with search bar ends here.-->
<!--other content.-->
<div class="sec1">
<h1 class="padding"><b>Administrators Login</b></h1><br>
<div class="sec">
<!--box with search bar starts here.-->
<form id='userForm'>
<h3>Username:</h3>
<input class='input' type='text' name='uname' value='' placeholder='Your username'><br>
<h3>Password:</h3>
<input class='input' type='password' name='paswd' value=''
placeholder='Enter your password' id="myInput"><br>
<p>
Show Password<input type="checkbox" onclick="myFunction()">
</p>
<br>
<div class='cnt'>
<input
style='font-size: 20px; background-color: #ff7a18; border-radius: 25px; width: 100px'
type='button' name='submit' value='Login'
onclick='sendInfo(this.form);'><br> <br></div>
</form>
<p id='result'></p>
<p style='font-size:20px'> <a class="nav-link active" href="./login.html">To go back to users login page click here!</a> </p>
<p style="font-size: 25px" id='result'></p>
</div>
</div>
</main>
<!--Footer starts here.-->
<footer>
<section class="mb-4" id="b">
<!--Section heading-->
<h2 class="h1-responsive font-weight-bold text-center my-4">Contact
Us</h2>
<!--Section description-->
<p class="text-center w-responsive mx-auto mb-5">Do you have any
questions? Please do not hesitate to contact us directly. Our team
will come back to you within a matter of hours to help you.</p>
<div class="row">
<div class="col-md-9 mb-md-0 mb-5">
<form id="contact-form" name="contact-form" action="mail.php"
method="POST">
<div class="row">
<div class="col-md-6">
<div class="md-form mb-0">
<input type="text" id="name" name="name" class="form-control">
<label for="name" class="">Your name</label>
</div>
</div>
<div class="col-md-6">
<div class="md-form mb-0">
<input type="text" id="email" name="email" class="form-control">
<label for="email" class="">Your email</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="md-form mb-0">
<input type="text" id="subject" name="subject"
class="form-control"> <label for="subject" class="">Subject</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="md-form">
<textarea id="message" name="message" rows="2"
class="form-control md-textarea"></textarea>
<label for="message">Your message</label>
</div>
</div>
</div>
</form>
<div class="text-center text-md-left">
<a class="btn btn-primary"
onclick="document.getElementById('contact-form').submit();">Send</a>
</div>
<div class="status"></div>
</div>
<div class="col-md-3 text-center">
<ul class="list-unstyled mb-0">
<li><i class="fas fa-map-marker-alt fa-2x"></i>
<p>Visamäentie 35 A, 13100 Hämeenlinna</p></li>
<li><i class="fas fa-phone mt-4 fa-2x"></i>
<p>(+358) 23456 789</p></li>
<li><i class="fas fa-envelope mt-4 fa-2x"></i>
<p>[email protected]</p></li>
</ul>
</div>
</div>
</section>
<div class="container">
<div class="py-3 my-4">
<ul class="nav justify-content-center border-bottom pb-3 mb-3">
<li class="nav-item"><a class="nav-link px-2 text-muted">Facebook</a></li>
<li class="nav-item"><a class="nav-link px-2 text-muted">Instagram</a></li>
<li class="nav-item"><a class="nav-link px-2 text-muted">LinkedIn</a></li>
<li class="nav-item"><a class="nav-link px-2 text-muted">Discord</a></li>
</ul>
<p class="text-center text-muted">© 2022 HAMK, Team 14</p>
</div>
</div>
</footer>
<!--Footer ends here.-->
<script>
function sendInfo(form){
var admin=new Object();
admin.uname=form.uname.value;
admin.paswd=form.paswd.value;
var jsonAdmin=JSON.stringify(admin);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML =
this.responseText;
if (this.responseText=="Error"){
document.getElementById("result").innerHTML =
"Username or/and password are wrong";
}
else{
window.location.assign("../php/admin.php");
}
}
};
xmlhttp.open("POST", "../php/admin_login.php", true);
xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xmlhttp.send("admin=" + jsonAdmin);
}
</script>
<script>
function myFunction() {
var x = document.getElementById("myInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
</script>
</body>
</html>
Solution 1:[1]
use the session for displaying the message and unset it after display that variable so that, it is not come again
$_SESSION['message'] = "Invalid username or password!";
if($_SESSION['message']!=''){
echo $_SESSION['message'];// display the message
unset($_SESSION['message']);// unset the message, so it is not come again in same page
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Elikill58 |
