4

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;
}
?>
giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
  • possible duplicate of [Using $_POST information only once](http://stackoverflow.com/questions/8171227/using-post-information-only-once) – Gian Nov 18 '11 at 01:53

3 Answers3

13
<?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.

Kai Qing
  • 18,793
  • 5
  • 39
  • 57
1

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.

Qasim
  • 1,686
  • 4
  • 27
  • 51
0

When you reload the page, the browser will send the same request that it sent for theoriginal page.

You want a POST-Redirect-GET.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964