如何不使用Sessions等指定方法在PHP单文件中保存表单POST历史提交数据
问题原因
HTTP是无状态协议,每次提交表单都会触发PHP脚本重新执行,你原有代码中每次提交时都会重新初始化$agenda为空数组,自然只能保留最新提交的单条数据,历史记录会被清空。
解决方案
利用单文件可自我读写的特性,将历史提交的数组直接固化到当前PHP文件的代码定义中,每次提交后更新数组定义并写回文件,下次请求就能直接读取到所有历史数据,完全符合禁用规则要求。
完整可运行代码
<?php // <<<AGENDA_STORAGE>>> $agenda = array ( ); // <<<AGENDA_STORAGE_END>>> if (isset($_POST['activity']) && isset($_POST['time']) && !empty($_POST['activity']) && !empty($_POST['time'])) { // 新增当前提交内容到数组 $newItem = trim($_POST['activity']) . ' ' . trim($_POST['time']); $agenda[] = $newItem; // 读取当前文件完整内容 $currentFileContent = file_get_contents(__FILE__); // 生成最新的数组定义代码 $newArrayDefine = '$agenda = ' . var_export($agenda, true) . ';'; // 替换历史数组定义部分 $currentFileContent = preg_replace( '#// <<<AGENDA_STORAGE>>>\s*(.*?)\s*// <<<AGENDA_STORAGE_END>>>#s', "// <<<AGENDA_STORAGE>>>\n" . $newArrayDefine . "\n// <<<AGENDA_STORAGE_END>>>", $currentFileContent ); // 写回当前文件完成更新 file_put_contents(__FILE__, $currentFileContent); } ?> <html> <head> </head> <body> <!-- 表单上方展示所有历史提交 --> <?php if (!empty($agenda)): ?> <h3>所有提交记录</h3> <?php foreach ($agenda as $item): ?> <p><?php echo htmlspecialchars($item); ?></p> <?php endforeach; ?> <hr> <?php endif; ?> <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST"> <label for="Activity">Activity</label><br> <input name="activity" type="text" required><br><br> <label for="Time">Time</label><br> <input name="time" type="time" required><br><br> <input type="submit" value="提交"> </form> </body> </html>
注意事项
运行前需要确保该PHP文件对服务端运行进程(如www-data、apache用户)有可写权限,Linux环境下可执行chmod 755 你的文件名.php配置权限。
内容的提问来源于stack exchange,提问作者Xitomz
相关产品推荐
相关产品推荐

