Dan, it's all done through the magic of IP Address caching and sessions...
When a user logs in, the IP address is bounced against a DB to identify the location, and the appropriate flag is shown... (This can sometimes be inaccurate due to ynamically assigned IP address, proxies and firewalls, but works well enough)
A session is usually created (or a cookie is set) and the user is identified as being online. When the session expires, via a timeout, or by logging out, the user is no longer online (to that site).
It can all be done with PHP (and some sort of D😎. It can be done with flat files, but that can be bulky , cumbersome and inefficient.