JeffCoderr JeffCoderr - 5 months ago 20
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("");
$updateCurrentTotal = $getTotal + 1;
$logFile = fopen("total.txt", "w");
$totalLogs = $updateCurrentTotal;
fwrite($logFile, $totalLogs);

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
reached around
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?


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);  
    fwrite($handle, $count);    
    flock($handle, LOCK_UN);    //Unlock File
} else {
    echo "Could not Lock The File!";