View Full Version : How do I write to a certain part of a text file using PHP??

04-09-2003, 12:47 AM
I wanna do sumthing where I can write wether a person is on or not. If they are not logged on the beginning of the text file that is being read will say OFF, and vise versa. But that wont be the only info in the text file, but that will be the first line. What could I do to make the PHP change only the first line????????????????????? Any help would be greatly appreciated!:)

04-09-2003, 01:47 AM
I had a similar problem with this, and this is how I went about dealing with it.

You know the first line of the text file is the attribute of what the user is doing (off or on)

when you read your file:

$id = 'nameOfFile.txt';
$file = file($id); //this is to make all the lines into an array
$handle = fopen($id, "r+");
flock($handle, 2); //lock the file from any other changes but the one this script makes
$length = count($file); //what is the length of the array
$file[0] = "ON"; //or "OFF" either way...

fclose(fopen($files,'w')); //open, empty and close a file

for ($i = 0; $i < $length; $i++)
echo $file[$i].'<br />';
fputs($handle, $file[$i]);
}//end for

fputs($handle, $comment);
flock($handle, 3); //unlock the file, so there is only one change at a time ie. no information will be lost
fclose($handle); //close the file

Note: that this script hasn't been tested, but this is the gist of what you have to do. The comments should help you figure out the rest if the code doesn't entirely work. Good luck.