Page 1 of 1
PHP code for Visitors in my site
Posted: Mon Dec 26, 2011 4:25 am
by johnmergene
I just want to have a code for counting my visitors in my site.. take note: (Visitors not Visits).. in every minute, it will check how many is visiting in my site..
without using Database.... cause my visitors dont have a login account....
then after knowing how many visitors in my site.. i wnt to print it on my page.. thats all..
maybe printing it in my page i can.. but the only php part. i dont know. thanks
Re: PHP code for Visitors in my site
Posted: Mon Dec 26, 2011 11:10 pm
by s.dot
Well, you will need to have some sort of storage mechanism for each unique visitor.
The logic would go like this:
* Probably determine unique visitors by IP Adress $_SERVER['REMOTE_ADDR']
* A timeout that determines whether a person is 'online' or not. (html is static and stateless, therefore you can't determine who's actually on, but rather who has been on in the last X minutes)
* A script that checks ips and timestamps to clean the list of 'old' ip addresses and count the total that have been active within your timeout period
Re: PHP code for Visitors in my site
Posted: Tue Dec 27, 2011 12:09 am
by s.dot
I wrote up a sample script, untested. You can try it. It only reads and write to the data file once per load so it's good in that respect. It might do an unnecessary loop, I'm not sure.
Code: Select all
<?php
$statsFile = 'visitors.txt'; //needs to be writable by web server, acts as data storage
$timeOut = 300; //5 minute timeout
function getIPs($line)
{
$line = explode(':', $line);
return $line[0];
}
$visitorInfo = file($statsFile);
$ips = array_map('getIPs', $visitorInfo);
$newVisitors = array();
if (!empty($_SERVER['REMOTE_ADDR']))
{
if (in_array($_SERVER['REMOTE_ADDR'], $ips))
{
foreach ($visitorInfo AS $visitor)
{
$info = explode(':', $visitor);
if ($info[0] == $_SERVER['REMOTE_ADDR'])
{
$newVisitors[] = $_SERVER['REMOTE_ADDR'] . ':' . time();
} else
{
$newVisitors[] = $visitor;
}
}
} else
{
$newVisitors = array_merge($visitorInfo, array($_SERVER['REMOTE_ADDR'] . ':' . time()));
}
}
$out = array();
foreach ($newVisitors AS $newVisitor)
{
$info = explode(':', $newVisitor);
if ($info[1] >= time() - $timeOut)
{
$out[] = $newVisitor;
}
}
file_put_contents($statsFile, implode("\n", $out), LOCK_EX);
echo count($out) . ' online';
Re: PHP code for Visitors in my site
Posted: Wed Dec 28, 2011 6:44 am
by johnmergene
im sorry sir, am inactive in a day..I will try it.. by the way. can post link here? so i can give u my Internet radio station site. os you can listen great songs.. lol. thanks a lot.
Re: PHP code for Visitors in my site
Posted: Wed Dec 28, 2011 6:53 am
by johnmergene
i tried it now. and it is working .. thanks bro.
Re: PHP code for Visitors in my site
Posted: Wed Dec 28, 2011 2:44 pm
by s.dot
No problem! Glad to help.
Go through it and play with it and tear it apart and make sure you understand it.

Ask questions if you don't. Here to help you learn!