【问题标题】:how do i put a php text on top of html我如何将 php 文本放在 html 之上
【发布时间】:2021-04-02 10:08:14
【问题描述】:

我有一个简单的聊天系统,我想做的是将新消息放在 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 文件上打印文本

【问题讨论】:

标签: php html


【解决方案1】:

您正在使用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);
 }
?>

【讨论】:

    【解决方案2】:

    只需删除 FILE_APPEND 标志,它不会覆盖文件,而是追加到末尾,然后使用 file_get_contents() 来连接两个文本字符串。

    <?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_get_contents("../log.html"), LOCK_EX);
     }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      相关资源
      最近更新 更多