Using GeoIP in PHP is simple thanks to the free MaxMind GeoIP Lite City database. These examples will show how to fetch a page visitors local, sunrise and sunset time based on their IP address.
Start out by downloading the MaxMind GeoIP Lite City.
You will also need to download the PHP API.
There are other methods, such as an Apache module or a PHP C extension. They are faster, but harder to setup. Unless you plan on doing thousands of queries per second, the PHP API is sufficient.
Extract the database files and the API into the same folder, and then create an empty PHP file.
Paste the content of the snippet below. It will get the visitor location based on their IP and show you the local time and GMT offset for the users time zone.
<?php
//Include dependencies
include("src/geoipcity.inc");
include("src/geoipregionvars.php");
include("src/timezone.php");
//Get remote IP
$ip = $_SERVER['REMOTE_ADDR'];
//Open GeoIP database and query our IP
$gi = geoip_open("GeoLiteCity.dat", GEOIP_STANDARD);
$record = geoip_record_by_addr($gi, $ip);
//If we for some reason didnt find data about the IP, default to a preset location.
//You can also print an error here.
if(!isset($record))
{
$record = new geoiprecord();
$record->latitude = 59.2;
$record->longitude = 17.8167;
$record->country_code = 'SE';
$record->region = 26;
}
//Calculate the timezone and local time
try
{
//Create timezone
$user_timezone = new DateTimeZone(get_time_zone($record->country_code, ($record->region!='') ? $record->region : 0));
//Create local time
$user_localtime = new DateTime("now", $user_timezone);
$user_timezone_offset = $user_localtime->getOffset();
}
//Timezone and/or local time detection failed
catch(Exception $e)
{
$user_timezone_offset = 7200;
$user_localtime = new DateTime("now");
}
echo 'User local time: ' . $user_localtime->format('H:i:s') . '<br/>';
echo 'Timezone GMT offset: ' . $user_timezone_offset . '<br/>';
You might wish to change the default location values on line 18-22 and 38-39. They are used if the IP is not in the database. Be aware that the defaults will trigger when you are working on a local server, as your IP will be local, and not in the database. You can use print_r($record); on your public IP to get all the values associated with the GeoIP record.
Sunrise, sunset
Did you know that PHP has dedicated functions for figuring out the time of sunrise and sunset? It’s easy to use, start out with the example above, and then you add:
echo 'Sunrise: ' . date_sunset(time(), SUNFUNCS_RET_STRING, $record->latitude, $record->longitude, ini_get("date.sunset_zenith"), ($user_timezone_offset/3600)) . ' <br/>';
…to get the local sunrise time. For sunset, the function is:
echo 'Sunset: ' . date_sunset(time(), SUNFUNCS_RET_STRING, $record->latitude, $record->longitude, ini_get("date.sunset_zenith"), ($user_timezone_offset/3600)) . ' <br/>';
The full result should look something like this:
User local time: 23:32:13
Timezone GMT offset: 7200
Sunrise: 03:51
Sunset: 21:40