我有一个php的简单聊天脚本,它没有数据库,工作正常。但它创建并存储所有聊天记录在文件中msg.html我想在一段时间后删除这些聊天记录。如何在大约30分钟后删除这些聊天。
Php代码在下方
<?php
if (isset($_GET['msg'])){
if (file_exists('msg.html')) {
$f = fopen('msg.html',"a+");
} else {
$f = fopen('msg.html',"w+");
}
$nick = isset($_GET['nick']) ? $_GET['nick'] : "Hidden";
$msg = isset($_GET['msg']) ? htmlspecialchars($_GET['msg']) : ".";
$line = "<p><span class='"name'">$nick: </span><span class='"txt'">$msg</span></p>";
fwrite($f,$line."'r'n");
fclose($f);
echo $line;
} else if (isset($_GET['all'])) {
$flag = file('msg.html');
$content = "";
foreach ($flag as $value) {
$content .= $value;
}
echo $content;
}
?>
请帮帮我…
最好的解决方案是使用cron
。您可以每X分钟执行一次清理PHP脚本,如下所示:
0,30 * * * * /path/to/php /path/to/cleanup_script.php
如果你想清空文件,那很容易——你只需要使用file_put_contents($file, '');
如果你想删除特定的消息,你需要在每行的开头添加一个时间戳(你可以在输出聊天时删除它),并在清理脚本中解析它。
注意
您可以通过在命令行上运行which php
来获得php的路径。