PHP 脚本在刷新后执行

我有一个按钮,单击后执行 php 代码(我正在使用电子邮件测试某些内容,到目前为止一切正常,除了“刷新后加载 PHP 脚本”问题):


HTML:


<form method="post"> 

<input type="submit" name="button1"

        class="button" value="Button1" /> 


<input type="submit" name="button2"

        class="button" value="Button2" /> 

</form>

PHP:


<?php

    if(array_key_exists('button1', $_POST)) { 

        button1(); 

    } 

    else if(array_key_exists('button2', $_POST)) { 

        button2(); 

    } 

    function button1() { 

        echo "mail"; 

    } 

    function button2() {

            ini_set( 'display_errors', 1 );

            error_reporting( E_ALL );

            $from = "test@example.de";

            $to = "thisIsA@secret.de";

            $subject = "Betreff";

            $message = "Text";

            $headers = "From:" . $from;

            mail($to,$subject,$message, $headers);

            echo "Test email sent";

    } 

?>

当我第一次访问该站点时,在我按下其中一个按钮之前,一切正常,并且脚本未执行。太完美了 -> 但是当我刷新页面时,脚本就会在我按下按钮的情况下执行。


如何防止刷新后加载脚本?


泛舟湖上清波郎朗
浏览 100回答 1
1回答

拉丁的传说

显示这种消息通常称为“闪现消息”:显示出现过一次的消息,刷新后不再显示。您的问题来自浏览器的行为:如果页面是从 POST 请求加载的,那么如果用户点击刷新按钮,它将发出具有相同 POST 参数的新 POST 请求但你想要的是:如果一个页面是从 POST 请求加载的,那么如果用户点击刷新按钮,它将发出一个新的 GET 请求(当然:没有任何 POST 参数)可以使用session来实现,步骤如下:用户单击按钮(1 或 2)POST 到自身按钮1=按钮1或按钮2=按钮2页面处理请求(做邮件功能)页面重定向/刷新以显示先前保存在会话变量中的新消息。<?php&nbsp; &nbsp; session_start();&nbsp; &nbsp; if(array_key_exists('button1', $_POST)) {&nbsp; &nbsp; &nbsp; &nbsp; button1();&nbsp; &nbsp; }&nbsp; &nbsp; else if(array_key_exists('button2', $_POST)) {&nbsp; &nbsp; &nbsp; &nbsp; button2();&nbsp; &nbsp; }&nbsp; &nbsp; function button1() {&nbsp; &nbsp; &nbsp; &nbsp; $_SESSION["msg"] = "mail";&nbsp; &nbsp; &nbsp; &nbsp; echo "<script>window.location = window.location.pathname;</script>";&nbsp; &nbsp; &nbsp; &nbsp; exit();&nbsp; &nbsp; }&nbsp; &nbsp; function button2() {&nbsp; &nbsp; &nbsp; &nbsp; ini_set( 'display_errors', 1 );&nbsp; &nbsp; &nbsp; &nbsp; error_reporting( E_ALL );&nbsp; &nbsp; &nbsp; &nbsp; $from = "test@example.de";&nbsp; &nbsp; &nbsp; &nbsp; $to = "thisIsA@secret.de";&nbsp; &nbsp; &nbsp; &nbsp; $subject = "Betreff";&nbsp; &nbsp; &nbsp; &nbsp; $message = "Text";&nbsp; &nbsp; &nbsp; &nbsp; $headers = "From:" . $from;&nbsp; &nbsp; &nbsp; &nbsp; mail($to,$subject,$message, $headers);&nbsp; &nbsp; &nbsp; &nbsp; $_SESSION["msg"] = "Test email sent";&nbsp; &nbsp; &nbsp; &nbsp; echo "<script>window.location = window.location.pathname;</script>";&nbsp; &nbsp; &nbsp; &nbsp; exit();&nbsp; &nbsp; }?><form method="POST"><input type="submit" name="button1"&nbsp; &nbsp; &nbsp; &nbsp; class="button" value="Button1" /><input type="submit" name="button2"&nbsp; &nbsp; &nbsp; &nbsp; class="button" value="Button2" /></form><?phpif(!empty($_SESSION["msg"])){&nbsp; &nbsp; echo $_SESSION["msg"];&nbsp; &nbsp; $_SESSION["msg"] = null;&nbsp; &nbsp; unset($_SESSION["msg"]);}?>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5