JeffCoderr JeffCoderr - 3 months ago 8
PHP Question

PHP - Data stored in txt file randomly deleted?

Ok, so I had a number stored in a txt file on my server, this number would increment whenever a user visited a certain page on my site, here's the code i wrote in order to increment the number in the txt file

$getTotal = file_get_contents("http://www.example.com/total.txt");
$updateCurrentTotal = $getTotal + 1;
$logFile = fopen("total.txt", "w");
$totalLogs = $updateCurrentTotal;
fwrite($logFile, $totalLogs);
fclose($logFile);


Yes i know the code isn't pretty and i should have just stored the number in my database, but i was lazy and decided to use a txt file.. But yeah back to my question, I noticed that when the number stored within
total.txt
reached around
30000
it randomly got reset to zero or it got deleted or something... I have no idea why this would of happened and was hoping someone here could help explain?

Answer

Here is an example for how to lock files and writes counter:

$handle = fopen("filetest.txt","r+");

//Lock File
if(flock($handle, LOCK_EX)) {
    $count = fread($handle, filesize("filetest.txt"));    
    $count = $count + 1;    //Increment by 1
    ftruncate($handle, 0);  
    rewind($handle);           
    fwrite($handle, $count);    
    flock($handle, LOCK_UN);    //Unlock File
} else {
    echo "Could not Lock The File!";
}


fclose($handle);
Comments