there is no really good working way to realise this.
the http protocol has no connection-controlling, so there is no way the webserver knows if the client is still on his page or not.
you have to write a little workaround like you say: hey, when my user has an idle-time of X minutes he isn't surfing on my page any more.
you may write a script which is called by every link the user can klick and which store's the last link-klick's timestamp of an user in the DB.
in another script you count how much timestamps < X minutes in your DB is stored, this is the number ob active users...