重定向到同一页面php后避免重新提交表单

时间:2016-01-23 14:48:14

标签: php forms post

我在互联网上搜索过但我仍感到困惑。我有一个表单,我提交并重定向到自己。然后它将变量回显到屏幕。但是,如何在用户点击刷新按钮后阻止表单重新提交?这是可以实现的吗?这是代码

            <!DOCTYPE HTML> 
        <html>
        <head>
        </head>
        <body> 

        <?php
        // define variables and set to empty values
        $name = $email = $gender = $comment = $website = "";

        if ($_SERVER["REQUEST_METHOD"] == "POST") {
           $name = test_input($_POST["name"]);
           $email = test_input($_POST["email"]);
           $website = test_input($_POST["website"]);
           $comment = test_input($_POST["comment"]);
           $gender = test_input($_POST["gender"]);
           echo "<h2>Your Input:</h2>";
        echo $name;
        echo "<br>";
        echo $email;
        echo "<br>";
        echo $website;
        echo "<br>";
        echo $comment;
        echo "<br>";
        echo $gender;
        }
        if($_SERVER["REQUEST_METHOD"] == "GET")
        {
            header('Location: '. $_SERVER['PHP_SELF'] , true, 303);
        }

        function test_input($data) {
           $data = trim($data);
           $data = stripslashes($data);
           $data = htmlspecialchars($data);
           return $data;
        }
        ?>

        <h2>PHP Form Validation Example</h2>
        <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
           Name: <input type="text" name="name">
           <br><br>
           E-mail: <input type="text" name="email">
           <br><br>
           Website: <input type="text" name="website">
           <br><br>
           Comment: <textarea name="comment" rows="5" cols="40"></textarea>
           <br><br>
           Gender:
           <input type="radio" name="gender" value="female">Female
           <input type="radio" name="gender" value="male">Male
           <br><br>
           <input type="submit" name="submit" value="Submit"> 
        </form>

我是新手......请帮助。

1 个答案:

答案 0 :(得分:0)

简单地说,如果帖子值存在,请不要显示提交按钮或删除提交按钮的行为,如此

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
       Name: <input type="text" name="name">
       <br><br>
       E-mail: <input type="text" name="email">
       <br><br>
       Website: <input type="text" name="website">
       <br><br>
       Comment: <textarea name="comment" rows="5" cols="40"></textarea>
       <br><br>
       Gender:
       <input type="radio" name="gender" value="female">Female
       <input type="radio" name="gender" value="male">Male
       <br><br>
       <?php if(!isset($_POST["name"])) { ?>
       <input type="submit" name="submit" value="Submit">
       <?php } ?>
    </form>