Use a table in your database to insert the ID's of the ones who logged in together with a timestamp.
Whenever a page is loaded, run a script that deletes the entries that are older than say 15 minutes and check that the current logged in user is in that table.
That way anyone who's been inactive for the last 15 minutes will be displayed as offline, and as soon as they click a page somewhere they will re-active since the script will insert them again if they were deleted, assuming they are still logged in.
Obviously there are many approaches to doing this, but by using only php it won't be real-time.