Mehdi Achour
Hello all,
Thanks in advance. I have a quesetion about writing to files. I am successfully opening a file and writing to it, but I'm having problems inserting text. My file currently has the following structure:
*************** [index] 24 1073946700 ***************
The second line in the file represents an incremented number. And the third line is a unix timestamp of when the incremented number was last incremented. I will have a script that will allow a user to decrement this number, and revert back to the timestamp that goes along with the decremented value.
Basically, my file will need the following structure:
*************** [index] 3 1073946709 1073946704 1073946700 ***************
Since the incremented number is at 3, there should be 3 timestamps in a "stack" order. Overwriting the sole number for incrementing or decrementing is no problem. However, inserting a new timestamp is where I get stuck. The current timestamp is over-written rather than inserting a new one.
Here is my code:
<? function hitcount($pagename) { $ctrPos; $timeStampPos; $buffer = ''; $formatName = '[' . $pagename . ']'; $fileHandle = -1;
//Make sure the file exists if(file_exists("Reports/hitcount.txt") == TRUE) { //Attempt to open the file with read AND write priveleges $fileHandle = fopen('Reports/hitcount.txt','r+');
//Make sure we have a valid file pointer if($fileHandle) { //Attempt to seek to the given page name section $buffer = fgets($fileHandle, 1024); while(!feof($fileHandle) && $buffer != $formatName . "\r\n") { $buffer = fgets($fileHandle, 1024); }
//Make sure we are not EOF if(feof($fileHandle) == FALSE) {
//get the current pointer position $ctrPos = ftell($fileHandle);
//read the next line which is the current hit count $buffer = fgets($fileHandle, 1024); $timeStampPos = ftell($fileHandle);
//increment the hit count $buffer = $buffer + 1;
//seek to where we know the hit count is fseek($fileHandle, $ctrPos);
//overwrite the hit count fwrite($fileHandle, $buffer . "\r\n");
//insert the new time stamp fwrite($fileHandle, time() . "\r\n"); } else { //We ARE EOF so we need to add the new page name here and insert the first hit count and timestamp fwrite($fileHandle, $formatName . "\r\n"); fwrite($fileHandle, "1\r\n" . time()); } } rewind($fileHandle); echo("File Contents: <BR>***************<BR>"); while(!feof($fileHandle)) { $buffer = fgets($fileHandle, 1024); echo($buffer . "<BR>"); } echo("***************<BR>"); fclose($fileHandle); } } ?>
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php