首页 > 解决方案 > 我如何将 php 文本放在 html 之上

问题描述

我有一个简单的聊天系统,我想做的是将新消息放在 html 之上。我的脚本将新消息放在底部,我想更改它。

<?php
 session_start();
 if(isset($_SESSION['name'])){
 $text = $_POST['text'];
 
 $text_message = "<div class='msgln'><span class='chat-time'>".date("m.d.y")."</span><br> <b 
 class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<p></div>";
 file_put_contents("../log.html", $text_message, FILE_APPEND | LOCK_EX);
 }
?>

该脚本在干净的 log.html 文件上打印文本

标签: phphtml

解决方案


您正在使用file_put_contents()函数附加文件内容,因此新添加到文件中的内容最终将到达底部。

我会为您的问题建议一个解决方法。首先将您的log.html文件内容保存到一个变量中,将新添加的消息覆盖到文件中(覆盖整个文件),最后将您保存的日志文件内容附加到文件中。这样,您可以使新内容始终显示在文件顶部。

<?php
 session_start();
 if(isset($_SESSION['name'])){
 $text = $_POST['text'];
 $file_content = file_get_contents("../log.html");
 $text_message = "<div class='msgln'><span class='chat-time'>".date("m.d.y")."</span><br> <b 
 class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<p></div>";
 file_put_contents("../log.html", $text_message);
 file_put_contents("../log.html", $file_content, FILE_APPEND | LOCK_EX);
 }
?>

推荐阅读