Im at the final stage of writing a chat room in PHP. Im currently attemting to put a "who's online" pane into the room.
So far i've managed to add new users to the file when they enter the room using the following function:
function addtousers($username){
$userfile = fopen('users.txt', 'r+');
fseek($userfile, 0, SEEK_END);
$userlist = file('users.txt');
if(count($userlist)==0){
fputs($userfile, $username);
} else {
fputs($userfile, "\n".$username);
}
fclose($userfile);
}
[/COLOR]
My problem comes when trying to remove a user from the room. What should happen is the following:
- save contents of users.txt into an array.
- open users.txt with 'w+' attribute.
- loop through the array each time writing the usernames in the array to the file. If a username to be written matches the username to be removed, dont write it.
For which I wrote the following function:
function removeuser($username){
$userlist = file('users.txt');
$userfile = fopen('users.txt', 'w+');
foreach($userlist as $i){
if($i!=$username){
fputs($userfile, $i);
}
}
fclose($userfile);
}
[/COLOR]
This works fine if only one user is in the users.txt file, but when 2 or more users are in I get strange things written to the file.
Anyone know whats up?