This is what I am currently using, but my script records the IP of the visitors and the members as well, so that I can show who is online with their respective country flags based on the remote address.
Since I don't know your database instructures, I will use a simple script of which you can build what you are trying to make..
First, we need to detect the IP address of the browser...
$ip = $_SERVER['REMOTE_ADDR'];
Once we know about the IP address, we can pass that on to the hostip.info API to get the flag. hostip is not 100% is sluggish during redundant query.. So, I suggests for you to store the information gathered in your own database. The API returns two letter country codes.
Second, based on the ip above we can send our query to the API for the country flag to show on the page. We can use the codes below to do just that. Here is the complete script..
Depending on the requesting traffic from the hostifp.info, your IP and flag specific to the country of your IP should be showing on this Demo. I am using the same script above with minor modification..