Why POST['submit'] is set when I reload?

2019-02-15 07:37发布

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 post submit
3条回答
Lonely孤独者°
2楼-- · 2019-02-15 07:50

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.

查看更多
Luminary・发光体
3楼-- · 2019-02-15 08:06
<?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.

查看更多
The star\"
4楼-- · 2019-02-15 08:06

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

You want a POST-Redirect-GET.

查看更多
登录 后发表回答