Php 限制聊天日志的大小
下面我将创建基于php/jquery的聊天应用程序 简而言之,此代码将消息放入日志:Php 限制聊天日志的大小,php,javascript,jquery,html,chat,Php,Javascript,Jquery,Html,Chat,下面我将创建基于php/jquery的聊天应用程序 简而言之,此代码将消息放入日志: <? session_start(); if(isset($_SESSION['name'])){ $text = $_POST['text']; $fp = fopen("log.html", 'a'); fwrite($fp, "<div class='msgln'>(".date("g:i A").") <b>".$_SESSIO
<?
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
Log
只是一个简单的HTML文档
如何将日志限制为仅显示最后100条消息?那个圆木不会变得太大吗?(超过1 MB)以下内容应该是您想要的:
$lines = file('log.html');
// get line number 2 - 100
if(count($lines) > 100) $lines = array_slice(1, 99);
// convert newlines to <br/> and append
$lines[] =
nl2br("<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
file_put_contents('log.html', join("\n", $lines));
$lines=file('log.html');
//得到2-100号线
如果(计数($lines)>100)$lines=array\u切片(1,99);
//将换行符转换为
并追加
$lines[]=
nl2br(“(.date(“g:IA”)”)。$_SESSION['name']。:“.stripslashes(htmlspecialchars($text))。”
”;
文件内容('log.html',join(“\n”,$line));
是否要将日志限制为仅包含100条消息,还是仅在文件大小达到阈值时显示100条并剪切?(1MB)
(我想知道当你只显示100条信息时,你如何处理100多条信息?)
但是当添加一条新消息时,您可以检查日志中是否已经有100条消息(如果是真的),删除第一条(最旧的)消息并附加最新的消息
由于您不知道消息的长度,因此需要读取整个文件内容并手动计算消息数(例如,通过计算substr'div class=\'msgln\'')并完全重写日志(表示模式“w”)。您可以这样做(可能会有更好的解决方案)
函数loadLog(){
$.ajax({
url:“log.html”,
cache:false,
成功:函数(html){
$(“#聊天室”).filter(函数(索引){
回归指数<100;
}).html(html);//将聊天日志插入#chatbox div
},
});
}
$lines = file('log.html');
// get line number 2 - 100
if(count($lines) > 100) $lines = array_slice(1, 99);
// convert newlines to <br/> and append
$lines[] =
nl2br("<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
file_put_contents('log.html', join("\n", $lines));
function loadLog(){
$.ajax({
url: "log.html",
cache: false,
success: function(html){
$("#chatbox").filter(function (index) {
return index < 100;
}).html(html); //Insert chat log into the #chatbox div
},
});
}