I am looking for a PHP script that can take an ip address and return the country where that ip address belongs to.
If you know or have been using such a script, please let me know.
What you need first is to get a database that matches IPs to countries/cities/locations.
Since IP to country is used alot in log analysis, you probably already have one installed on your php server if you rent one. Cpanel (common web based linux server administration panel) for example usually comes together with Awstats (analyses raw linux log files) which has an IP-country database.
The php script of course will be specific to the database structure of the IP-to-Country Database you are using. Some databases will already have premade scripts too.
An easy way to get IPs converted to countries withought setting up the IP-to-country database and writing the php script for the db, is to use a webservice that does this for you and provides an API interface to geocoding (converting data to a location) IP addresses.
Note: usually you wouldn't just use $_SERVER as that is sent to your server as a HTTP Header, and can be tampered with (unlikely but still). So you should treat it as user submitted data and "clean" it. Also, theres a few different predefined variables that get the IP, for different setups, theres a few functions out there just for getting the right one.
Using a web services is easier I believe, and avoids having a huge database and load on your server, but it is a bit slower and dependant on the availablility of the remote server that you are connecting to.