Forum Moderators: coopster
I want to edit a .txt file using php.
The scenario is this:
When a window is closed by a user of my site I want the php to find a .txt file and remove a line(s) from it. Is this possible?
If not is it possible any other way you can think of?
Any help or pushing in the right direction would be great.
<If not is it possible any other way you can think of?>
Yes..
- Open the file for read.
- Read the file line-by-line into an array.
- Close the file.
- Open the file for write.
- Loop beginning with the first value of the array and ending with the last.
- Check each value of the array to see if it's the one you want to delete. If it's not, then write it back to the file. If it is, then don't.
- Close the file.
The basic idea would be...
<?php
$fname = "test.txt";
$exclude = "some string";
$lines = file($fname);
$out = "";
foreach ($lines as $line) {
if (strstr($line, $exclude) == "") {
$out .= $line;
}
}
$f = fopen($fname, "w");
fwrite($f, $out);
fclose($f);
?>
Jordan
I want the php to edit the text file to remove a users name from the list when they leave.(close browser window)
If there is a php onUnload then great, if not I could just have an html small popup with php in it open when the browser window is closed.
The text file is in the same folder as the chat page.
<The actual use is for a java chatroom. At present is saves the chat box and the users in the room to two text files. When you close the window and reopen it, the user name is still there and noone knows you have left>
If this is the use, then you may have another issue.
If the user closes the window all happy the way you intend, then no problem. But there are other circumstances under which this won't work. For instance, they could get booted offline with the window left open, or their machine could crash. In either of these two cases, they would technically no longer be in the chatroom, but their name would still be in your text file.
You may want to see if you can setup time sort of polling system. For instance, you have javascript in the chat window that, once per minute, contacts the server and says "I'm still here." If the server doesn't receive that, then it removes the user from the text file.
This way, if their machine crashes or they get booted offline before they can close the window properly, it will still mark them offline in no more than 60 seconds. Of course, you could make this happen every 10 seconds if you want. The more frequently you do it, the more up-to-date the list of people online will be, but the more strain it would put on your server and its bandwidth.
One way to accomplish this may be to have a 0-pixel frame (can you have a frame that's 0 pixels?, if not, then 1) at the top of the chat window. In this frame is code that can meta-refresh every x seconds sending over an "I'm still here" signal with an ID unique to that person logged in, so the server knows who "I" am when sending the signal.