I am trying to create a visitor counter on my wordpress website using the following code:
add_action( 'init', 'session_counter' );
function session_counter() {
$date = date('d/m/Y');
$session_data = get_option( 'session_counter');
$session_data['01/12/2020'] = 0;
$session_counter = 0;
$session_data_output = '';
$i = 0;
if (!session_id()) {
session_start();
if($_SESSION['hasVisited'] != '1'){
if(isset($session_data[$date])){
$session_counter = $session_data[$date];
}
$session_data[$date] = $session_counter + 1;
update_option( 'session_counter', $session_data);
foreach($session_data as $k => $v){
if($i > 0){
$session_data_output .= "\n";
}
$session_data_output .= $k." - ".$v;
$i++;
}
$session_counter_txt = fopen("counter.txt", "w");
fwrite($session_counter_txt, $session_data_output);
fclose($session_counter_txt);
}
$_SESSION['hasVisited'] = '1';
}
}
The code above stores the total count of visitors per day in the database and then as a readable format in a text file.
The purpose of having a visitor counter was to see how many people are accessing the website before they consent to the GDPR popup because Google Analytics is only enabled after a consent has been given. The website uses CookieYes GDPR popup which also records the consents.
Everything works fine except if I compare the text file to Google Analytics and CookieYes, I am seeing significantly higher count in the text file than in Google Analytics. For example, the text file would show a total day count of 11764 while Google Analytics would show a total day count of 598.
After further investigation, I noticed that the same website visitor is getting recorded few times in the text file than in Google Analytics and making me believe that the website session keeps refreshing while the same visitor is browsing the website.
I always assumed sessions are refreshed if I clear my browser history or if I close the browser, so why does the session keeps refreshing for the same user.
I dont want to record the sessions by IP addresses as I want to keep the IP anonymous for GDPR purposes.
Is there something wrong in my code with the way I am storing sessions? How do I prevent the sessions from refreshing for the same user? I only want the session to be destroyed after the visitor closes the browser.