Detecting Country, Using IP Address

This is a simple and funny way to integrate MySQL, PHP, XML and Flash.
A basic understanding of these topics is required, as I won't go into too many details.

This is all based on the .csv file available at http://ip-to-country.webhosting.info/. You can download the file here.
As the countries' flags are also available at http://ip-to-country.webhosting.info/node/view/91, I use them as well. I converted all of them (using Fireworks MX 2004) to .jpg, as it's the only format that can be loaded into Flash.

The first step is creating a database, and then using a PHP script to load all the info contained in the .csv file into the database's table.
This very same script is also used to update the database, as before it starts introducing the new values, it deletes all the existing ones.

I created two PHP files and two Flash movies - one that outputs XML and another that only outputs variable name/value pairs.
The flash file is very simple: two or three text fields respectively, and an empty movie clip - everything created dynamically. The flash file triggers the PHP script, and then loads the respective content.

Here's an example:

You should see your country's name and flag. If this doesn't happen, it's likely that the database is out of date and doesn't contain your IP address yet.

You can download all the files here.

Creating the table:

SQL:
  1. CREATE TABLE iptocountry (
  2. ip_from double DEFAULT NULL,
  3. ip_to double DEFAULT NULL,
  4. country_code2 char(2) DEFAULT NULL,
  5. country_code3 char(3) DEFAULT NULL,
  6. country_name varchar(50) DEFAULT NULL
  7. ) TYPE=MyISAM;

This code creates a table called iptocountry - in the currently selected database (test) - with 5 columns, e.g.:

  • ip_from - [33996344]
  • ip_to - [33996351]
    these two values provide the ip range - [33996344 to 33996351]
  • country_code2 (the country code with two characters) - [GB]
  • country_code3 (the country code with three characters) - [GBR]
  • country_name - [UNITED KINGDOM]

Inserting values in the table
Like said before, a PHP script reads the .csv file, and inserts the values into the table:

PHP:
  1. <?php
  2. // connect to the database
  3. $db = mysql_connect ("localhost","username", "password") or die ("can't connect to database");
  4. mysql_select_db ("test", $db) or die ("can't select database");
  5.  
  6. // delete existing records
  7. $query = "DELETE FROM iptocountry";
  8. $result = mysql_query ($query, $db);
  9.  
  10. // open the .csv file for reading
  11. $fp = fopen ('iptocountry.csv', 'r');
  12.  
  13. while (!feof ($fp)){
  14.  
  15. // read each line of the text file
  16. $row = fgets ($fp, 4096);
  17.  
  18. // transform each line into an array
  19. $data = explode ("\"", $row);
  20.  
  21. // attention - there are country names with single quotes: COTE D'IVOIRE
  22. // which require the use of addslashes()
  23. $data[9] = addslashes ($data[9]);
  24.  
  25. // store the useful values in the table iptoucoutry
  26. $query = "insert into iptocountry VALUES ('$data[1]','$data[3]','$data[5]','$data[7]','$data[9]')";
  27. $result = mysql_query($query, $db);
  28. }
  29.  
  30. // close the connection to the database
  31. // close the file
  32. fclose ($fp);
  33. ?>

PHP output - XML
Another PHP script queries the database, and outputs the results in XML format:

PHP:
  1. <?php
  2. // get user's ip address
  3. $ip = $_SERVER['REMOTE_ADDR'];
  4. // change the ip's format
  5. $ip_new = sprintf ("%u", ip2long($ip));
  6.  
  7. // connect to the database
  8. mysql_connect ("localhost","user","password") or die ("can't connect to database");
  9. mysql_select_db ("test") or die ("can't select database");
  10.  
  11. // query the database
  12. // find the country_name and the country_code2 inside the specified ip range
  13. // select only one value
  14. $query = "SELECT country_name, country_code2 FROM iptocountry WHERE ip_from <= $ip_new && ip_to>= $ip_new LIMIT 1";
  15. $result = mysql_query ($query);
  16. $row = mysql_fetch_array ($result);
  17.  
  18. // output the result in XML format
  19. echo '<?xml version="1.0" encoding="UTF-8"?>';
  20. echo '<country>';
  21. echo '<details name="'.$row['country_name'].'" code="'.$row['country_code2'].'"/>';
  22. echo '</country>';
  23. ?>

PHP output - variables
Alternatively, a similar script outputs variable name/value pairs:

PHP:
  1. <?php
  2. // exactly the same as above, except for the XML part
  3.  
  4. $country = $row['country_name'];
  5. $country_2 = $row['country_code2'];
  6.  
  7. // output the variables
  8. echo "&name=$country&code=$country_2&ip=$ip";
  9. ?>

The only thing missing is the Flash movie and the corresponding code:

Flash movie - XML

Actionscript:
  1. // the url that you use both to the scrip and to the flags' folder
  2. var url = "http://localhost/php/";
  3. /*
  4. create the text fields
  5. for the country name and code
  6. */
  7. this.createTextField("coutry_txt", 1, 0, 0, 100, 40);
  8. this.createTextField("code_txt", 2, 0, 50, 100, 40);
  9. /*
  10. create an empty movie clip to hold the flag
  11. and position it
  12. */
  13. this.createEmptyMovieClip("flag_mc", 3);
  14. flag_mc._y = 100;
  15. /*
  16. create the my_xml XML Object
  17. to hold the xml data created by the php script getCountryXML.php
  18. */
  19. var my_xml = new XML();
  20. my_xml.ignoreWhite = true;
  21. // when the xml loads show the country name and code, and the flag
  22. my_xml.onLoad = function(success)
  23. {
  24. if (success) {
  25. var temp_xml = this.firstChild;
  26. trace(temp_xml);
  27. // country name
  28. var name_xml = temp_xml.childNodes[0].attributes.name;
  29. trace(name_xml);
  30. // country code
  31. var code_xml = temp_xml.childNodes[0].attributes.code;
  32. trace(code_xml);
  33. // show text:
  34. coutry_txt.text = "your country is:\n" + name_xml;
  35. code_txt.text = "the country code is:\n" + code_xml;
  36. // show flag
  37. flag_mc.loadMovie(url + "flags/" + code_xml.toLowerCase() + ".jpg");
  38. // an error occurred
  39. } else {
  40. trace("an error occurred");
  41. }
  42. };
  43. my_xml.load(url + "getCountryXML.php");

Flash movie - variables
Similarly, this code loads the variables:

Actionscript:
  1. var url = "http://localhost/";
  2.  
  3. /*
  4. create the text fields
  5. for the country name and code and ip
  6. */
  7.  
  8. this.createTextField("coutry_txt", 1, 0, 0, 100, 40);
  9. this.createTextField("code_txt", 2, 0, 50, 100, 40);
  10. this.createTextField("ip_txt", 4, 0, 120, 100, 40);
  11.  
  12. this.createEmptyMovieClip("flag_mc", 3);
  13. flag_mc._y = 100;
  14.  
  15. /*
  16. create the my_lv LoadVars Object
  17. to hold the variables that come from the php script getCountry.php
  18. */
  19.  
  20. var my_lv = new LoadVars();
  21. // when the variables load, show the country name and code, and the flag
  22. my_lv.onLoad = function(success)
  23. {
  24. if (success) {
  25. // country name
  26. trace(this.name);
  27. // country code
  28. trace(this.code);
  29. // ip
  30. trace(this.ip);
  31.  
  32. // show text:
  33. coutry_txt.text = "your country is:\n" + this.name;
  34. code_txt.text = "the country code is:\n" + this.code;
  35. ip_txt.text = "the ip is:\n" + this.ip;
  36.  
  37. // show flag
  38. flag_mc.loadMovie(url + "flags/" + this.code.toLowerCase() + ".jpg");
  39. // an error occurred
  40. } else {
  41. trace("an error occurred");
  42. }
  43. };
  44. my_lv.load(url + "getCountry.php");

Comments are closed.