如何将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文件上打印文本

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

只需删除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);
}
?>

最新更新