In php i'm setting the flag for visitor visiting my website in database(it is '1' when they are visiting), if the user closes the page, it will end the session and update their flag in database as '0'
There has been a similar request a few weeks ago. This might help: https://forums.digitalpoint.com/threads/php-members-online.2690567/