Problem:
I need a precise visitor counter that only records distinct visitors, whether they visit daily or weekly, for a user post system that ranks the most viewed posts on the homepage. Using Google Analytics is not an option.
This PHP code implements the required functionality:
<?php session_start(); // start Session, if not already started $visitors = array(); // store visitors IP addresses in a PHP array $ip = $_SERVER['REMOTE_ADDR']; // get visitor's IP address $dt = time(); // get current timestamp $expiration = 86400; // expire session in 24 hours if(isset($_GET['view'])) { // check if 'view' is a query parameter if(!isset($_SESSION['last_visit']) || ($_SESSION['last_visit'] < ($dt - $expiration))) { // visitor hasn't visited in the last 24 hours (or ever) $_SESSION['last_visit'] = $dt; // update last visit timestamp $visitors[] = $ip; // add IP to the visitors array $view_count = $view_count + 1; // increment view count } } // output data echo 'Total Unique Visitors: ', count($visitors); echo '<br>'; echo 'Total Page Views: ', $view_count; ?>
How it works:
Remember: For this code to work, you need to include it on every page you want to track views for, and you need to add the following HTML code to the pages:
<a href="?view=1">View Post</a>
The above is the detailed content of How to Count Unique Visitors to Your Site Using PHP?. For more information, please follow other related articles on the PHP Chinese website!