Page 1 of 1

Can you tell how many IPs are visiting the site at one time?

Posted: Tue Jun 18, 2013 11:24 am
by simonmlewis
I've been asked if there is a means in PHP to register, for example, an IP address each time someone visits.
When they leave the site, it deletes that IP address in a DB - thus seeing at any one moment how many "people" are on the site.

I know how to log the IP when they visit (easy of course), but I don't know how to delete it when they close their browser or leave the site entirely.

We had an issue once when I wanted to sign them out when they left the site, but we had an issue where it ran the script when they just left the page for another page on the site.

So it's the latter bit I am stuck on. If possible - this would be amazing as the site gets very high traffic and be very cool!!

Trying to use this:

Code: Select all

$result = mysql_query ("SELECT ipaddress FROM usersonsite WHERE ipaddress = '$iplog'");
$num_result = mysql_num_rows($result);
if ($num_result == NULL)
{
mysql_query("INSERT INTO usersonsite(ipaddress) VALUES ('$iplog')");
}
?>
<body onunload="bye()"> 
<script>
function bye()
 {
 var php_value = 2;
 var address = "loggedusers?php_value="+php_value
 document.getElementById('im1').src = address
 }  
 </script>
So at first it checks if the IP is in the database, if it isn't, it INSERT it.
then if the body us unloaded, it runs the bye() script which triggers loggedusers.php. That script deletes the IP address.

Trouble is - it isn't working!! The INSERT works, but nothing I do will make the loggedusers.php run.
I've tried onunload, onbeforeunload etc. Is there a foolproof method? I understand this will be a JAVASCRIPT thing, so perhaps it should be in that section instead.

I'm just thinking there must be a way, either in PHP or with PHP and Javascript.
It's just so I can show on screen how many users are onscreen - preferably by showing how many IPs are logged in a DB at any one time.

Re: Can you tell how many IPs are visiting the site at one t

Posted: Tue Jun 18, 2013 12:54 pm
by requinix
There is no good way to tell when a user "leaves your site". Javascript methods are unreliable and don't cover all scenarios. A better way to tell is by inactivity: after, say, 15 minutes the person is no longer browsing.

Keep a table of IP addresses with a unique value stored in a cookie - perhaps the session ID. That value is how you really tell uniqueness. On every page load update the "last active" timestamp. Then your count of active users is a count of people in the table with a last active date within the last X minutes.

For example, also storing the user agent and number of page views and making use of ON UPDATE CURRENT_TIMESTAMP,

Code: Select all

CREATE TABLE `visitors` (
	`SID` VARCHAR(32) NOT NULL, /* or however long your SIDs are */
	`ip` VARCHAR(40) NOT NULL,
	`useragent` VARCHAR(500) NOT NULL,
	`views` BIGINT UNSIGNED NOT NULL DEFAULT 0,
	`lastactive` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, // updates automatically
	PRIMARY KEY (`SID`, `ip`),
	INDEX (`lastactive`)
)

Code: Select all

session_start();

$SID = session_id();
$ip = $_SERVER["REMOTE_ADDR"];
$useragent = /* escaped value of $_SERVER["HTTP_USER_AGENT"] */;
$query = "
	INSERT INTO `visitors` (`SID`, `ip`, `useragent`)
	VALUES ('{$SID}', '{$ip}', '{$useragent}')
	ON DUPLICATE KEY UPDATE `views` = `views` + 1
";
To help limit the size of the table you can set up a cron job that deletes inactive records.

Re: Can you tell how many IPs are visiting the site at one t

Posted: Tue Jun 18, 2013 1:57 pm
by simonmlewis
Do you know what, about an hour ago I had a similar idea, without session IDs.
When they connect, it checks if their IP is logged. If it isn't, it runs an INSERT with their IP and datetime stamp.
If it IS in the system, it simply runs an UPDATE. But here's the clever bit, the timestamp it adds is 5 minutes ahead of time.

Then, as each user visits the site, the script checks if there are any datetime stamp older than the current time. If there are, it removes them.

You therefore have a "fairly" accurate log of those on the site within the last 5 minutes.

Does that sound fairly efficient?

Re: Can you tell how many IPs are visiting the site at one t

Posted: Tue Jun 18, 2013 2:47 pm
by requinix
- IP addresses aren't unique to users. That's why I brought up using SIDs.
- The INSERT...ON DUPLICATE KEY thing I used is equivalent to your INSERT/UPDATE but has the advantage of being atomic with only one query.
- Using times five minutes in the future seems more complicated. The end result is the same but you're storing times that haven't happened yet. If I were new to the code I would find that confusing and wonder if maybe the machine's clock was wrong... I suppose you could just label the time as "when their current browsing session ends" instead of "when they visited".

Re: Can you tell how many IPs are visiting the site at one t

Posted: Tue Jun 18, 2013 2:52 pm
by simonmlewis
IP address is unique to the computer. That is what's important to me. Not bothered if one person visits it on the PC, and then a second person goes on it on a different "session". It's like a guide to visitors on there.
I don't know what you mean about being "atomic" with only one query?

Re: Can you tell how many IPs are visiting the site at one t

Posted: Tue Jun 18, 2013 4:01 pm
by requinix
simonmlewis wrote:IP address is unique to the computer.
No. It isn't. It's unique to a computer or cluster of computers. I have five computers at home and as far as your website is concerned they all have the same IP address. College dorms often have a single address as far as your website is concerned. Here at work we have a dozen employees and far more computers and they all have the same IP address as far as your website is concerned.

Re: Can you tell how many IPs are visiting the site at one t

Posted: Wed Jun 19, 2013 3:25 am
by simonmlewis
Oh I see what you mean.
Yes this isn't an "exact number" I am looking for. But I do get your point. If three people from the same house are visitng the site, then that shows ONE user. And if that is happening across a thousand houses, we are missing 3000 users! (is that right?).

So how do you create Session IDs as I have never done that? Do you randomly create a 7 digit number and assign it to a session?

Re: Can you tell how many IPs are visiting the site at one t

Posted: Wed Jun 19, 2013 1:23 pm
by requinix
You don't. PHP does it for you when you call session_start(). After you've called it you can grab the ID with session_id.

Re: Can you tell how many IPs are visiting the site at one t

Posted: Thu Jun 20, 2013 3:11 am
by simonmlewis
Got it:

Code: Select all

$sessionid = session_id();

if(isset($_SESSION['sessionid']))
{
$_SESSION['sessionid']=$_SESSION['sessionid'];
}
else
{
$sessionid = session_id();
}
Works a treat. And I am still using the timedate with 5 mins +. So it's kinda gives an estimate of those online in the last 5 minutes.