The http protocol doesn't cater for the broswer leaving a page - since it could be a page change or simply closing the browser. Therefore there is no way to automatically tell when people leave your page.
The usual method is to put new sessions into a database witha timestamp. The piece of code for showing how many people are online simply accesses the database and counts how many sessions were started say 5,10,15 minutes ago. You may also need to delete older entries or the database gets huge!!
If you want to force a more accurate method of counting I suppose you could launch the database in a window which the user cannot close directly. You then supply a button to close the window/exit the site. This tells the database to delete that session and then the window closes. They are most irritating however. Not to mention the ghosts that would haunt your site forever if like me you constantly surf the net with your fingers on Alt-F4. I'd say that users would grudge this method for the relatively small enhancement it provides.
BG