Making visitors online script

Hi to all
I want to create a function that returns into a variable the number of visitors who they are online in my site.I am thinking to do this working with session_id() . Can someone help me giving me some general instructions or thoughts how I can do this? Any other idea is welcome.

define users that are online.

1 Like

I’m not sure you can do this in JS. I have a PHP script which shows the number of users online. I logs each IP address in a SQLite database removing an IP address if it hasn’t been active for 3 minutes.

1 Like

In general, I recommend to do it this way:

$users_online = rand(20,30);

This number is as reliable and useful as any other, yet it you have it with much less hassle.

The session_id is useful for this action?

why should it be?

Because it should be more accurate than IP address?

1 Like

@colshrapnel you mean combined with the logging from @Gandalf? As a standalone solution i think i would prefer your rand() over session_id().

Are sessions stored in the file system or in a database table?

I am going to do a php code to store the session_id into my database. The visitors are not subscribers,members or something like that.So i don’t know if I can get the visitor id with someway and store it in my database.

I appreciate your humor but i want to learn from this process.By the way you have right about the number…:lol:

Ok, if you realize that this number is deliberately unreliable, here is what you can do, given you are using PDO.

Create a table consists of 2 fields, sid and utime, making sid an unique key

then run three queries, one to add the current hit

$pdo->prepare("REPLACE INTO online VALUES (?, now())")->execute([session_id()]);

one to clean up the stalled sessions

$pdo->query("SELECT FROM online WHERE utime < NOW() - INTERVAL 3 MINUTE");

and finally one to count active users

$online = $pdo->query("SELECT count(1) FROM online")->fetchColumn();
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.