Stop repeat the actions on the page after submit the form
I made this "sign in" form and made a error messages to appear if the fields is empty and other error messages.
my request is:
After the "sign in" fails how to stop the fields from resubmit the values again when hit F5 or reload the page.
<?php
ob_start();
session_start();
include "config/config.php";
include "includes/functions/check.php";
$userName = $passWord = "";
$userNameErr = $passWordErr = $loginErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['user_name'])) {
$userNameErr = "User name is required";
} else {
$userName = check_input($_POST['user_name']);
if (!preg_match("/^[a-zA-Z ]*$/", $userName)) {
$userNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST['password'])) {
$passWordErr = "Password is required";
} else {
$passWord = check_input($_POST['password']);
}
$loginUser = $db->prepare("SELECT * FROM hired_person_info WHERE user_name=? AND password=?");
$loginUser->bind_param('ss', $userName, $passWord);
if ($loginUser->execute()) {
$results = $loginUser->get_result();
if ($results->num_rows == 1) {
$row = $results->fetch_object();
$_SESSION['name'] = $row->full_name;
$_SESSION['log'] = 1;
print_r($_SESSION);
header("Location:?pid=4");
} elseif (!empty($_POST['user_name']) && !empty($_POST['password'])) {
$loginErr = "Invalid Login Information";
}
}
}
ob_flush()
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Administration Panel</title>
<link href="../css/adminStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 id="head" class="header_height"></h1>
<div class="contentLogin">
<div class="login_bg">
<div id="header">
<p>login</p>
</div>
<div id="form">
<?php
echo $loginErr;
?>
<form action="<?php htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label for="user_name" class="text_login">User name</label>
<input type="text" name="user_name" id="user_name" value="<?php echo $userName ?>">
<?php echo $userNameErr; ?>
<br/><br/>
<label for="password" class="text_login">Password</label>
<input type="password" name="password" id="password">
<?php echo $passWordErr; ?>
<br/>
<div id="submit">
<input type="submit" value="Sign in" name="submit" id="submit" class="btn">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Instead of using if($_SERVER["REQUEST_METHOD"] == "POST"){ try using the post name of your submit button. So the condition will be as follows,
if(isset($_POST['submit'])) {
}
Within this you can put all your codes. I am not telling that the condition you have used is wrong, but it may create conflict when you will put another form in the same page.
And after your operation completed, success or fail, does not matter just unset the post variable.
unset($_POST);
To completely avoid the resend functionality you need to redirect your page to the same page once. For that just save your error message in session and redirect to login page again. Then checking if session value for message exists then display your message.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am trying to display the errors on the same page if anyone entered invalid login details
but when invalid login details are entered a message is displayed called Array? Not sure why that's happening.
In this code, there is a login form and if user logs in then log in, a success message appears but when details are invalid a message should appear "invalid details" which is not appearing
<?php
// starting session
session_start();
// calling connection
require('/home/s3022041/sqlC/dbConnect.php');
$message = "";
$role = "";
if($_SERVER['REQUEST_METHOD'] == "POST"){
//Array to hold any errors in updated data
$errors = array();
//Checking entered email
if(empty($_POST['username'])){
$errors[] = "username address required";
}
else{
$username = $_POST['username'];
if(filter_var($_POST['username'], FILTER_VALIDATE_EMAIL)) {
$username = $_POST['username'];
}
else {
$errors[] = "Invalid username";
}
}
if(empty($_POST['password'])){
$errors[] = "passwrod required";
}
else{
$password = validating_input($_POST['password']);
}
if(isset($_POST["btnLogin"]))
{
$username = $_POST["username"];
$password = $_POST["password"];
// retrieving user data
$query = "SELECT * FROM user WHERE username = '$username' AND password='$password'";
// executing query
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
// if user logs in
if($row["role"] == "user") //|| ($row["role"] == "admin"))
{
//Creating session variables to hold relevant information about who is logged in
$_SESSION['User'] = $row["username"];
$_SESSION['Role'] == $row["role"];
// redirecting to home page after 5 seconds..
header( "refresh:5;url=index.php" );
$text = "<h4>Welcome {$_SESSION['User']}</h4>";
$text1 = "<h4>welcome to kiddies,</h4>";
$text2 = "<h5>you'll be redirected in 5 seconds...</h5>";
}
// if admin logs in
elseif($row["role"] == "admin")
{
//Creating session variables to hold relevant information about who is logged in
$_SESSION['Admin'] = $row["username"];
$_SESSION['Role'] == $row["role"];
//redirecting to home page after 5 seconds..
header( "refresh:5;url=temp/adminDshboard.php" );
$text = "<h4>Welcome {$_SESSION['Admin']}</h4>";
$text1 = "<h4>welcome to kiddies,</h4>";
$text2 = "<h5>you'll be redirected to <strong>admin panel</strong> in 5 seconds...</h5>";
}
}
}
}
else
{
echo "$errors";
header("location : login.php");
}
}
?>
<?php
include "header.php";
?>
<!doctype html>
<html lang="en">
<head>
<link rel="icon" type="image/png" href="images/logo_transparent.png"/>
<link href="../assets/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="Mystyle.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.card{
padding: 2rem;
}
.global-container{
margin-top: 10rem;
margin-bottom: 5rem;
}
.welcome{
padding: 3rem;
background-color: white;
color: black;
font-weight: bold;
font-family: 'Cherry Swash';
font-size: 15rem;
}
</style>
</head>
<body>
<div class="container">
<div class="col-12 col-md-6">
<div class="global-container">
<?php
if((isset($_SESSION['Admin'])) || (isset($_SESSION['User'])))
{
echo "<div class='welcome'>$text";
echo "$text1";
echo "$text2</div>";
}
else
{
?>
<div class="card login-form">
<div class="card-body">
<h3 class="card-title text-center">Log in to Kiddies Cove</h3>
<div class="card-text">
<!--
<div class="alert alert-danger alert-dismissible fade show" role="alert">Incorrect username or password.</div> -->
<form method="POST" action="login.php">
<!-- to error: add class "has-danger" -->
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="username" class="form-control form-control-sm" id="exampleInputEmail1" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control form-control-sm" id="exampleInputPassword1">
</div>
<button type="submit" name="btnLogin" class="btn btn-primary btn-block">Sign in</button>
<?php echo "<h1>$errors</h1>"; ?>
<div class="sign-up">
Don't have an account? Create One
</div>
</form>
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
//Function which validates inputData
function validating_input($inputData){
$inputData = trim($inputData);
$inputData = stripslashes($inputData);
$inputData = htmlentities($inputData, ENT_QUOTES);
return $inputData;
}
?>
I am giving simple example assuming your code is from login.php
then you can edit as per your requirement.
#it is just a example how to show errors. Data sanitization, preventing sql injection etc is not considered in this example.
<?php
include('db.php');
$error = false;
if((isset$_POST['action']) && ($_POST['action']=="loginnow")){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($usernane)){
$error= true;
$msg[]= " Enter Username";
}
if(empty($password)){
$error= true;
$msg[] = "Enter Password";
}
if (!$error){
// check if username and password matches and redirect to index.php. successfully login
}else{
$msg[] = " Invalid Username or Password";
}
}
?>
in html body, above your form, put
<?php
if(isset($msg)){
foreach($msg as $err)[
echo $err."<br>";
}
}
?>
<form method="post" action="">
<input type="hidden" name="action" value="loginnow">
Username : <input type="text" name="username">
Password : <input type="password" name="password">
<input type="submit" name="submit" value="Log In">
</form>
So I'm making a Login - Successful Login page with PHP, and using MySQL Database. My code successfully checked the Username and Password and only allowed me to head to the next page once they are correct.
However, I cannot print out the Username on Successful Login page. So I'm not sure if my session is running properly or not.
login.php
<!DOCTYPE HTML>
<html>
<?php
session_start();
?>
<head>
<title>Login</title>
</head>
<body>
<!--<form action ="SuccessfulLogin.php" method = "get"> --> // If I put this in my code, the whole program stops checking Username and Password, and just put me to the next page
<?php
//define variables and set to empty values
$nameErr = $loginErr = "";
$Username = $website = $Password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Username"])) {
$nameErr = "Name is required";
} else {
$Username = test_input($_POST["Username"]);
}
if (empty($_POST["Password"])) {
$passErr = "Password is required";
} else {
$Password = test_input($_POST["Password"]);
}
//continues to target page if all validation is passed
if ( $unameErr ==""&& $passErr ==""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$hashpass=hash('sha256',$Password);
$sql="SELECT * from Members WHERE Username ='$Username' AND Password='$hashpass';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database");
$a=mysqli_num_rows($result);
if ($a===0){
$loginErr="Invalid username or password";
}else{
$_SESSION["Username"]=$Username;
header('Location: /SuccessfulLogin.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Login </h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
User Name: <input type="text" name="Username" value="<?php echo $Username;?>"/>
<span class="error">* <?php echo $unameErr;?></span>
<br/><br/>
Password:
<input type="text" name="Password" value=""/>
<span class="error">* <?php echo $passErr;?></span>
<br/><br/>
<span class="error">* <?php echo $loginErr;?></span>
<input type="submit" name="submit" value="Login"/>
</form>
<!--</form>--> // closing tag of form action SuccessfulLogin.php
</html>
SuccessfulLogin.php
<!doctype html>
<html>
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
<head>
<meta charset="utf-8">
<title>Login Form</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<body>
<!--<form action ="MemberMenu.php" method = "get">-->
<h2><?php echo "User $Username LOGGED IN"; ?></h2> // Doesn't print out the $Username
<p align="center"> Click here to be redirected to the menu page </p>
<!--</form>-->
</footer>
</body>
</html>
you need to check session isset or not.
Change
<?php
session_start();
$Username=$_GET['Username'];
$_SESSION['Username']=$Username;
?>
With
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
echo $Username;
}
?>
You're using $_GET["Username"] which will be empty in this example, and then setting $_SESSION["Username"] to the empty variable.
Also this is a very odd way to do user auth.
Change this line of code
<?php
session_start();
$Username=$_SESSION['Username'];
$_SESSION['Username']=$Username;
?>
Into:
<?php
session_start();
$Username=$_SESSION['Username'];
?>
Read more about PHP session here
I have this line of code and I am trying to send an error message if the username password combination don't match, the thing is the message displays when I access the page, even before i enter a username and password. how do I make the message appear ONLY after login failed?
Thanks!!
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if(($user == "someusername") && ($pass == "somepassword"))
{
include("../securedfile.php");
}
else{
$message = "Invalid User/Password - Please Try Again";
echo "<script type='text/javascript'>alert('$message');</script>";
}
if(isset ($_POST))
{?>
<div class="secure">
<form method="POST" action="secure.php">
username:<input class="user" type="text" name="user"></input><br/><br/>
password:<input class="pass" type="password" name="pass"></input><br/><br/>
<button class="submit" type="submit" name="submit">SUBMIT</span></button>
</form>
</div>
<?}
}
?>
There is the parenthesis problem with the 'else', then the form is calling secure.php instead of calling itself, there's no isset...The rewritten code below would be a better way of doing it. And have checked it, it works. (The name of this whole file - new.php)
<div class="secure">
<form method="POST" action="new.php">
username:<input class="user" type="text" name="user"></input><br/><br/>
password:<input class="pass" type="password" name="pass"></input><br/><br/>
<button class="submit" type="submit" name="submit">SUBMIT</span></button>
</form>
</div>
<?php
// checking the user
if(isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "someusername" && $pass == "somepassword")
{
include("../securedfile.php");
}
else
{
$message = "Invalid User/Password - Please Try Again";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>
I have some data input area.Here is my file.
Here is my db.php:
<?php
$username = "root";
$password = "";
try {
$db = new PDO('mysql:host=localhost;dbname=task', $username, $password);
echo "Connection Successfull";
} catch (PDOException $e) {
die("Error: Database connection");
}
?>
And my index.php is:
<?php
include "db.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" value="Submit">
</form>
</div>
<?php
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
?>
</body>
</html>
When i first go to index.php page then it's showing some notice.
Notice: Undefined index: name in
C:\xampp\htdocs\techmasters\begin\index.php on line 21
Notice: Undefined index: email in
C:\xampp\htdocs\techmasters\begin\index.php on line 22
Notice: Undefined index: website in
C:\xampp\htdocs\techmasters\begin\index.php on line 23
but if i input any data then it going to be inserted fine.My problem is that if i reload the browser then previous inserted data going to inserted again.How can i solve this problem?
Thanks in advanced.
Its because, you are not checking whether form is submitted or not.
On every page request, data is getting inserted, add a check.
<?php
if (isset($_POST['name']) && ! empty($_POST['name'])) {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if (empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
}
else{
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
$_POST = NULL;
}
?>
This will ensure that database insert will be done only in case of form submit.
EDIT:
If you submit a form to same page and then reload the page, it will
ask you to resubmit the form. Either change method to get and check
for duplicity or submit the form to another file (move form submit
code to other file and set it as form action).
When you reload the page it's asking for form re-submission. When you click on resend then it will post all data again and inserted in database. To overcome this issue you can use jquery.
Try this code :
html file :
<!DOCTYPE html>
<html>
<head>
<title>This is title</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="wrap1">
<form method="POST" id="frm" action="">
<input type="text" name="name" required> Username</br></br>
<input type="email" name="email" required> Email</br></br>
<input type="text" name="website" required> Website</br></br>
<input type="submit" class="sub" value="Submit">
</form>
</div>
<script>
$(".sub").click(function (e) {
e.preventDefault();
$.post("test.php",$("#frm").serialize(),function(data){
if(data == "Inserted!") {
//You can reload your page here
} else {
//Display error message.
}
});
});
</script>
</body>
</html>
You php code (test.php) :
<?php
include "db.php";
if(isset($_POST['name']) && $_POST['name'] != "") {
$username = $_POST['name'];
$emailadd = $_POST['email'];
$webadd = $_POST['website'];
$sql = "INSERT INTO users (name,email,website) VALUES ('$username','$emailadd','$webadd')";
if(empty($username) || empty($emailadd) || empty($webadd)){
echo "Please input all field";
} else {
if ($db->query($sql)) {
echo "Inserted!";
}
else{
echo "Error";
}
}
$db = null;
exit;
}
?>
Don't forget to add jquery file in your html.
How can I hold the half entered details that a user when attempting to create a user for my webpage?
If, for example, the user only fills out the 'USERNAME' field, I want the error to flag, redirecting them back to the register page, but I want the fields that they previously entered to remain filled.
Any ideas please? :(
The Register Page
<!DOCTYPE html>
<html>
<head>
<title>The Classic - Vintage Cinema Reviews</title>
<link href="CSS.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="favicon.ico">
<meta name="description" content="A unique, ground-breaking website for all things relating to classical cinema. The Classic revolutionises the way that we see classic cinema, and provides the movie goer with an opportunity to find all the reviews they need!">
<meta name="author" content="Stefan Batterbee">
<meta charset="UTF-8">
</head>
<body>
<div id="page">
<header> <?php
session_start();
if(isset($_SESSION['Logged_In']))
{
header('Location: index.php');
}
else
{
echo '<br>';
echo 'You are not logged in!<br>';
echo 'Click here to log in,<br>';
echo 'or register below.';
}
?>
</header>
<nav>
<ul id="navigation">
<li>H O M E </li>
<li>F I L M R E V I E W S </li>
<li>A R T I C L E S</li>
<li>A B O U T U S</li>
</ul>
</nav>
<div id="breadcrumbs">
<a class="link" href="index.php">Home</a> > Register
</div>
<div id="main">
<centre>
<?php
if( isset($_SESSION['ERROR_MESSAGE']) && is_array($_SESSION['ERROR_MESSAGE']) && count($_SESSION['ERROR_MESSAGE']) >0 ) {
echo '<h3 style="color:#F00;">';
foreach($_SESSION['ERROR_MESSAGE'] as $msg) {
echo $msg;
}
echo '</h3><br>';
unset($_SESSION['ERROR_MESSAGE']);
}
?>
<br>
<center><h1>Welcome to The Classic!</h1><br>
<h3>You can create an account below to become an exclusive member of our website.<br>
Just simply fill our your details below, and we will create your account!<br>
<p>If you already have an account, please go to the log in page.</p></h3></center><br><br>
</centre>
<div id="loginbox">
<form method="post" action="regprocess.php">
<h3>Username:</h3>
<input type="text" name="username" value=""/><br>
<h3>Password:</h3>
<input type="password" name="password" /><br>
<h3>Confirm Password:</h3>
<input type="password" name="password2" /><br>
<h3>First Name:</h3>
<input type="text" name="fname" value=""/><br>
<h3>Surname:</h3>
<input type="text" name="lname" value=""/><br><br>
<input type="submit" name="submit" value="Create your account!" /><br><br>
Already a user? Log in <a class="link" href="register.php">HERE</a><br>
</form>
</div><br><br>
</div>
<footer>
<p class="textleft">Created by Stefan Batterbee (2013)</p>
<p class="textright">Click <a class="link" href="https://www.facebook.com/the.classic.cinema.reviews">HERE</a> to access our Facebook page.</p>
</footer>
</div>
</body>
</html>
The Processing Script
<?php
session_start();
include"config.php";
$error_message = array();
$error = false;
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if($username == '') {
$error_message[] = 'Please enter a username.';
$error = true;
}
if($password == '') {
$error_message[] = 'Please enter a password.';
$error = true;
}
if($password2 == '') {
$error_message[] = 'Please enter a confirmation of your password.';
$error = true;
}
if($fname == '') {
$error_message[] = 'Please enter a first name.';
$error = true;
}
if($lname == '') {
$error_message[] = 'Please enter a last name.';
$error = true;
}
if ($password != $password2)
{
$error_message[] = 'Your passwords did not match, please try again!';
$error = true;
}
if ($username && $password && $password2 && $fname && $lname != '' and $password == $password2) {
$insert = 'INSERT INTO USER(USERNAME, PASSWORD, FIRST_NAME, SURNAME) VALUES("'.$username.'","'.$password.'","'.$fname.'","'.$lname.'")';
}
mysql_query($insert);
header('location: log_in.php');
if($error) {
$_SESSION['ERROR_MESSAGE'] = $error_message;
session_write_close();
header("location: register.php");
exit();
}
?>
In each value spot of each input, echo the posted value of that input.
<h3>Username:</h3>
<input type="text" name="username"
value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>"/><br>
You check for isset first to see if it is in the post, and if it is, put it back into the input.
EDIT:
I forgot to add that you should do the processing on the same page, rather than doing a redirect. That is what allows the post values to stick around so you can refill them into the form. It will also make it no longer necessary to put your error message into a SESSION variable.
EDIT 2:
As was commented, you can also fill the post into the session. The reason I don't do this is that, if a) the session were hijacked, or b) it's a public computer and someone else sits down at it, the person's registration data would show up again on the registration form. If you choose to set the post values into the session, I strongly suggest that, at the end of printing out the form, you unset all the registration session values. They will be lost on a page refresh, but it's more secure for the user. It's a good idea to do this for your error message also, unless you want that error message to be stuck on the page forever. E.g.:
//after the </form> tag
unset($_SESSION['ERROR_MESSAGE']);
unset($_SESSION['username']);
// ... and so forth for the rest
As per your request:
Using sessions could work better if you're planning on using your code in two seperate pages.
You would first assign your session name to your POST name:
$_SESSION['username'] = $_POST['username'];
then using it inside your input element:
<input type="text" name="username" value="<?php if(isset($_SESSION['username'])) echo $_SESSION['username']; ?>"/>
That's what I use myself. It's another option.
However, using ob_start() is usually required when using sessions, by placing it on top of session_start(); yet required since you are using header(). Not using ob_start(); will result in an headers already sent error message.
For example:
<?php
ob_start();
session_start();
// ...
Footnotes: session_start(); must reside inside all files using the same session(s).