My application is a simple login page. When it fails, I print an error message. My question is, why when I reload the page the message is been printed again? How can I fix that?
The code is working fine, I've made another php file executing the database check & connection.
<?php
require_once("include/database.php");
if(isset($_POST['submit'])) {
connect_bookstore(); // custom function
$spassword = sha1($_POST['password']);
$username = $_POST['username'];
if ( checkpassword($username,$spassword) ) { //custom function
header('Location:insert.php');
exit;
} else {
$message = "Login failed!";
}
}
?>
Inside the html body.
<?php
if (isset($message)) {
echo $message;
}
?>
<?php
session_start();
require_once("include/database.php");
if(isset($_POST['submit'])) {
connect_bookstore(); // custom function
$spassword = sha1($_POST['password']);
$username = $_POST['username'];
if ( checkpassword($username,$spassword) ) { //custom function
header('Location:insert.php');
exit;
} else {
$_SESSION['message'] = "Login failed!";
header('location: /yourfile.php');
exit;
}
}
if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
Fundamentally, yes, post/redirect/get... but sometimes a simple explanation is better.
I use sessions to store flash messages, then display them like this.
Thats because you are resending the same POST data when you refresh, if you do a GET request you will notice in the URL your parameters that you are passing are there, so if you refresh those parameters are once again sent. Same thing with POST.
When you reload the page, the browser will send the same request that it sent for theoriginal page.
You want a POST-Redirect-GET.