Page 1 of 1
Telling how many people are on the site using PHP
Posted: Tue Jan 07, 2003 5:19 pm
by evilmonkey
I want to tell how many people are browsing my site right now. Can I do this using PHP?
Also I want to put in a hits counter. Can i do this using the onload function in HTML or is there a simpler way? How do I use the onload function? The current hits will be stored in a db, so it should be something like:
Code: Select all
<body "onload">
<?php
//connect to the db
$query="Select value From table";
$result=($query, $connection);
$value=$value+1
//and insert it back...
?>
</body>
Am i way off?
Thanks.
Posted: Tue Jan 07, 2003 5:23 pm
by Elmseeker
Yes, look at the bottom of the front page of these forums and you will see where it says who is logged in as well as how many guests (people not logged in). I am not sure exactly how it is done but most likely it uses a DB table and sessions to keep track of users.
[Edit]
Hmmm...just came across
This while browsing through phpclasses.org, think it's exactly what you asked for!
Posted: Tue Jan 07, 2003 8:54 pm
by evilmonkey
I can't seem to access the site although I registered. Weird. Can anyone else help?
Thanks
Posted: Tue Jan 07, 2003 9:34 pm
by hob_goblin
there are tons on
http://www.hotscripts.com/ look for "counters" and "real-time counters"
Posted: Tue Jan 07, 2003 9:43 pm
by heimei_lovely
you can use session to do this,when you open a page,it will start a session,and when you close the page,it will destroy the session.so it's easily to judge who's online,and how many people is online.Of course you must create a online table in the database.
Posted: Wed Jan 08, 2003 9:39 am
by DaiWelsh
If you create a sessions table something like
CREATE TABLE Sessions (
SessionID int Auto_Increment Primary Key
,SessionHits int
,SessionLastTime timestamp
)
Then on every page of your site check for a session variable (lets say $session_id), if it exists run a query to
UPDATE Sessions SET SessionHits = SessionHits + 1 WHERE SessionID = $session_id
if it doent exist then
INSERT INTO Sessions (SessionHits) VALUES (0)
and
SELECT LAST_INSERT_ID() As NewSession
then finally set the session variable to the New Session Id as just retrieved.
Then anywhere you want to get count of those online do
SELECT count(*) As NumOnline FROM Sessions WHERE SessionLastTime > Whatever time period you determine to be "active".
For a lighter load on the DB (but removes the hit counting) you can store a second session var with the time that you last updated the db for this user and only update the timestamp every 5 mins or so.
HTH,
Dai
Posted: Wed Jan 08, 2003 7:14 pm
by evilmonkey
Thanks everyone, I'll take a look at what you have given me.
Cheers.