search
HomeBackend DevelopmentPHP Tutorialphp 刷新后 并没有POST 却输出数据

php post 刷新

我的php代码如下:


 
        网络留言板


                         //error_reporting(E_ALL & ~E_NOTICE);
        function write_message($file_name, $message)
        {
                $fp = fopen($file_name, "a");  //以追加模式打开文件
                if(flock($fp, LOCK_EX))
                {
                        fwrite($fp, $message);
                        flock($fp, LOCK_UN);
                }
                else
                {
                        echo "不能锁定文件
";
                }
                fclose($fp);   //关闭文件资源
        }

//自定义一个遍历读取文件的函数
        function read_message($file_name)
        {
                $fp = fopen($file_name, "r");  //以只读模式打开文件
                flock($fp, LOCK_SH);
                $buffer = "";

                while(!feof($fp))
                {
                        $buffer .= fread($fp, 1024);
                }

                $data = explode("", $buffer);
                unset($data[count($data)-1]);
                foreach($data as $line)
                {
                        $arr = explode("||", $line);
                        list($user_name, $title, $message) = $arr;
                        if($user_name != "" && $title != "" && $message != "")
                        {
                                echo $user_name.'说   ';
                                echo "     ".$title.'    ';
                                echo $message."
";
                        }
                }

                flock($fp, LOCK_UN);
                fclose($fp);
        }
                
//声明一个变量保存文件,在这个文件中保存留言信息
        $file_name = "text_date.txt";
        //判断用户是否提交按钮
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['user_name']) && !empty($_POST['title']) && !empty($_POST['mess']))
        {
                $message = $_POST['user_name']."||".$_POST['title']."||".$_POST['mess']."";
                write_message($file_name, $message);
        }

        if (file_exists($file_name))
        {
                read_message($file_name);
        }        
?>        
        
        

                用户名:

                标  题:

                

                
        
        


主界面如下:

添加了一条数据以后:
 
之后我不点击留言,直接按F5刷新,并没有POST,却在刷新后出现了相同的数据。如下图:
 
真的不明白啊,求解答啊……

回复讨论(解决方案)

       if (file_exists($file_name))
        {
                read_message($file_name);
        }        
只要 $file_name 指向的文件存在就输出
并没有其他方式控制不输出

可在读的同时,却向 text_date.txt文件中写数据。当你留言后,不点留言按钮,就是每刷新一次,就会向文件中写入刚才你留言的数据,然后再输出。

表单提交后用header做一个重定向比较好。

刷新表单返回页相当于重新提交!
你用的是什么浏览器?刷新表单返回页都没有提示的吗?

用的是google浏览器,
下面是我的一个小测试,提交之后,刷新就不会出现先前的情况。


 
网络留言板


//error_reporting(E_ALL & ~E_NOTICE);
function write_message($message)
{
echo $message;
}


//判断用户是否提交按钮
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['user_name']) && !empty($_POST['title']) && !empty($_POST['mess']))
{
$message = $_POST['user_name']."||".$_POST['title']."||".$_POST['mess']."";
write_message($message);
}
?>


用户名:

标  题:






你这2段代码 提交后再刷新页面,都是会重复提交的!!
只不过第2段代码你没有将数据写入文件,所以你看到的都是第1次提交的数据!!

获取数据后可以跳转一下!

function write_message($message){echo $message;echo "<script>location.href='';</script>";exit;}

提交后做个跳转吧,没做跳转,一直停留在提交后那里,只要你刷新,数据就会重复提交。

太感谢你们了,我明白了……真心谢谢大伙……

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools