截断文件('w')不适用于聊天应用程序

时间:2010-07-15 14:16:06

标签: php fopen truncate

我为网站制作了聊天应用程序。一切都工作正常,但是,我试图让用户点击“退出”的情况下,聊天框系统会向其他用户显示特定用户确实已经退出房间,然后它将继续清除用户屏幕上已注销的所有旧消息,如果用户回到同一个房间,他们将无法看到他们所拥有的任何旧对话。
保存聊天框中所有消息的文件是“log.html”。出于某种原因,我的代码之前部分工作正常,即当用户点击注销时log.html被截断,但是我永远无法得到用户确实已注销的log.html文件,现在两者都是不工作。有人可以查看我的代码并让我知道我是否做得对吗?顺便说一句,代码可能甚至不包含实际问题,但话又说,它可能会随意询问您是否需要更多信息。

此代码段来自group2.php,其中存储了聊天框:

session_start();  

if(isset($_GET['logout'])){     

//Simple exit message for chat log
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'><i>User ". $_SESSION['name'] ." has left the chat session.</i><br></div>");
fclose($fp);

    //Truncate the log file
     $fp = fopen("log.html", 'w');
     fclose($fp);

    session_destroy();
header("Location: main.php"); //Redirect the user        
                        }  

这也是group2.php中的一些代码,可能会有所帮助:

<div id="menu">
    <p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
    <p class="logout" name="logout" ><a id="exit" name="logout" href="#">Exit Group</a></p>
    <div style="clear:both"></div>
</div>  

我也在想,可能是,我需要回应一下用户已离开,并清除log.html文件,而不是在这段代码中?

//If user wants to end session
    $("#exit").click(function(){
        var exit = confirm("Are you sure you want to end the session?");
        if(exit==true){window.location = 'main.php?logout=true';}
    });  

1 个答案:

答案 0 :(得分:1)

如果我可能会问,为什么要清除文件:$ fp = fopen(“log.html”,“w”);之后写了几行?

我认为更好的解决方案是:

$fp = fopen("log.html", 'w');
fwrite($fp, "<div class='msgln'><i>User ". $_SESSION['name'] ." has left the chat session.</i><br></div>");
fclose($fp);

另外,我认为您可能需要在文件中写一些内容才能使truncate生效(按照说法)。所以,如果你想保留当前代码,添加一个fwrite($ fp,“”);在$ fp = fopen之后(“log.html”,“w”);

希望有所帮助!