3 steps to adding country detection to your site using php

Posted by by Sandy on 31st Oct, 2009

It is very easy to detect your users country and I’ll show you how using php.

Step 1 – Detect user IP address

PHP has wonderfully simple function do this. All you have to do is use:

$_SERVER['REMOTE_ADDR'];

We’re going to store this as a variable called ip:

$ip = $_SERVER['REMOTE_ADDR'];

Step 2 – Check location of IP address

We’re going check location of IP address with a function called locateip which uses the free geolocation API available at http://ipinfodb.com/

The locateip function has 4 sections as follows:

1. Make a request for an XML file from ipinfodb.com.
2. If first request fails make request to backup server.
3. Extract the country and country code from the XML.
4. Store everything in an array for convenience.

  
  function locateIp($ip){
	$data = file_get_contents("http://ipinfodb.com/ip_query_country.php?ip=$ip&output=xml");

	//Use backup server if cannot make a connection
	if (!$data){
		$backup = file_get_contents("http://backup.ipinfodb.com/ip_query_country.php?ip=$ip&output=xml");
		$answer = new SimpleXMLElement($backup);
		if (!$backup) return false; // Failed to open connection
	}else{
		$answer = new SimpleXMLElement($data);
	}

	$country_code = $answer->CountryCode;
	$country_name = $answer->CountryName;

	//Return the data as an array
	return array('ip' => $ip, 'country_code' => $country_code, 'country_name' => $country_name);
}

We would call the function using:

$ip_data = locateIp($ip);

Step 3 – Display on page

All we have to do now is display the information on the page using the array

echo $ip_data['country_name'];

You may wish to store details within session variables so you can use on multiple pages without having to perform the check again.

You can see the code in action at http://www.amgmedia.co.uk/country.php

I’ve went a little further and used the country code in combination with the free flag icons available from http://www.famfamfam.com to add the appropriate country flag. All the flags are named after the country code so it’s quite easy to do.

By making a slight change to the XML file requested from IPInfoDB you can also detect the users city with latitude and longitude. Check out the example at http://www.amgmedia.co.uk/location.php Although, this may not always be accurate depending on the users ISP. You will see I also added a map which is generated using the latitude and longitude and Google maps API.

IPInfoDB does not have a query limit as such but if you send an queries that are at a rate faster than 2 per second they will be put in “queue”. If you stay below 2 queries/second everything will be normal. If you go over the limit, you will still get an answer for all queries but they will be slowed down to about 1 per second.

If your not too happy about having to rely on using an API then IPInfoDB lets you download their IP database as SQL and use what ever method you choose to query it.

On both examples I have provided you can look at the code and try it out on your own. Although, if your testing on a local server your IP address will show as 127.0.0.1 depending on how you have configured your localhost.

That’s all folks!

  • Share/Bookmark

Exporting to Excel using PHP and MySQL

Posted by by Gavin on 2nd Aug, 2009

A support question we are sometimes asked by other developers is how to export information from web pages to an excel spreadsheet. This tutorial shows the key elements for exporting dynamic information from a database query.

so here  goes…

  1. <?php
  2. require_once (’lib/config.inc.php’);
  3. require_once (MYSQL);
  4. $filename =”excelreport.xls”;
  5. $q = “select * from student order by studentSurname, studentFirstName asc”;
  6. $r = @mysqli_query ($dbc, $q) or trigger_error(”Query: $q\n<br />MySQL Error: ” . mysqli_error($dbc));
  7. $contents =”Surname \tFirst Name\tEmail\tDOB\tAddress1\tAddress2\tTown\tPost Code\tSQA\t \n”;
  8. while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
  9. $contents .=”".$row['studentSurname'].” \t”.$row['studentFirstName'].”\t”.$row['studentEmail'].”\t”.$row['studentDOB'].”\t”.$row['studentAddress1'].”\t”.$row['studentAddress2'].”\t”.$row['studentTown'].”\t”.$row['studentPostCode'].”\t”.$row['studentSQA'].”\t  \n”;
  10. } //end of while loop
  11. header(’Content-type: application/ms-excel’);
  12. header(’Content-Disposition: attachment; filename=’.$filename);
  13. echo $contents;
  14. ?>

The above code explained -

Line 1 – kicks off the PHP code with the opening PHP tag.

Lines 2 and 3 – makes the database connection. I’ve stored by connection in a separate file called  config.in.php – I’m also using MySQLi (improved).

Line 4 sets up a variable for the file name.

Lines 5 and 6 – query the database for the information I’m looking for and stores the results in an array called $r.

Line 7 – sets up a variable called $contents and inserts the column headings for my excel spreadsheet.

Line 8 – starts are ‘while loop’ to extract information from the $r array from the query on the database.

Line 9 – appends the information for each result to the $contents variable.

Line 10- end the ‘while loop’.

Lines 11 and 12 – set up the file details for an excel spreadsheet.

Line 13 – echos the $contents variable.

Line 14 -closes the php code.

To try this out, replace the query in the code to a database you already have, update the database connection to your details then copy this code and save it as excel.php, then on any other page simply insert a link to it.

  • Share/Bookmark

Just came across this example of a website review meeting I thought you might find funny (It’s 3 minutes long).

Need a simple to understand and uncomplicated advice and help with your website? Get it touch with us about your Website Development requirements!

  • Share/Bookmark

This is what Web Development does to you…

Posted by by Dave on 25th Jun, 2009

So you want to be a web developer?  Have a look at these guys, you might change your mind…

Don’t do it to yourself, don’t do it to your family!

We’ll take care of the designing, coding and marketing. We’re too deep in this now, but we can help people like you escape! Just give us a call – we’ll take care of it  ;-)

  • Share/Bookmark