Reputation: 45
I'm creating a visitors counter for website. It needs to show visits in current month. This is the code:
<?php
if(file_exists('visitors.txt'))
{
$myFile = "visitors.txt";
$fh = fopen($myFile, 'r');
$myFileContents = fread($fh, 21);
fclose($fh);
echo $myFileContents;
$myFile2 = "visitors.txt";
$myFileLink2 = fopen($myFile2, 'w+') or die("Can't open file.");
$newContents = $myFileContents+1;
fwrite($myFileLink2, $newContents);
fclose($myFileLink2);
echo $newContents;
}
else
{
$myFile = "visitors.txt";
fclose($fh)
}
?>
It creates file visistors.txt and saves number of visits. Now how I can clean this file each new month and start counting from 0?
Upvotes: 1
Views: 47
Reputation: 23958
This is the basic idea.
I see if the file exists.
If yes, then i read the contents and add one to the count and save it to the file (overwriting the previous data).
If no, create the file with count 1.
$ym = date("Y-m"); // 2018-05
if(file_exists('visitors-' $ym . '.txt')){ // visitors-2018-05.txt
$count = file_get_contents('visitors-' $ym . '.txt');
$count++;
file_put_contents('visitors-' $ym . '.txt', $count);
}else{
file_put_contents('visitors-' $ym . '.txt', "1");
}
EDIT; this should work as long as you don't open and edit the contents yourself (accidently add a space or some other letter making $count++ fail.)
You can perhaps do $count = (int)file_get_contents('visitors-' $ym . '.txt');
but it's not completly safe.
If you need a foolproof solutiuon I think you need to regex the contents, but that is overkill and will drain memory and cpu for no good reason.
Just stay out of the file and only open it with code and you are safe.
EDIT again: Just a tip. In a few months you will have a lot of textfiles.
Save them in a separate folder to keep it clean in webroot.
Upvotes: 2