I\'m a beginner to PHP and I\'m writing some code to my site. I want to get the total number of sessions that is active at that instant. I knew this is some difficult task b
All websites that allow you to show the number of visitors use database sessions handlers (it could be mysql db or even memcached).
Sessions table structure:
CREATE TABLE `sessions` (
`id` INT NOT NULL ,
`session_id` VARCHAR( 32 ) NOT NULL ,
`user_id` INT NOT NULL ,
`last_seen` DATETIME NOT NULL
) ENGINE = InnoDB;
Session ID could be either built-in php session id or your own unique hash. Built-in session works not so fast, but you don't need to watch for generating session ids, expiry dates and other.
User ID would be the current logged in user id, or NULL if he's a guest.
Every time user refreshes the page you should update your session table:
At this point you can get all visitors count using simple sql query:
SELECT
COUNT(`user_id`) AS users,
(COUNT(*) - COUNT(`user_id`)) as guests
FROM
`sessions`
WHERE
`last_seen` >= DATE_SUB(NOW(), INTERVAL 15 MINUTE)