Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at Unwanted.cloud

RSS Latest posts from my personal blog


Subscribe to RSS feed


Get visitor local time, sunrise and sunset time by IP with MaxMind GeoIP and PHP

Stanislav KhromovStanislav Khromov

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

Full-stack impostor syndrome sufferer & Software Engineer at Schibsted Media Group

Comments 15
  • dossihost
    Posted on

    dossihost dossihost

    Reply Author

    hello and thank u a lot for the share,
    I noticed that in my time zone : Timezone GMT offset: 7200 the clock says one hour before the actuall time, Daylight saving time, how can i fix this?


  • Debanjan Ghosh
    Posted on

    Debanjan Ghosh Debanjan Ghosh

    Reply Author

    Hi,
    Can you tell me how to incorporate this in wordpress. I used to use wp-geolocation but it is very unreliable and also hasn’t been updated for 2 years.
    I really need a solution can help?

    Thanks,
    Debanjan Ghosh


  • Umair
    Posted on

    Umair Umair

    Reply Author

    Great tutorial it really helped me Thanks.


  • Lance
    Posted on

    Lance Lance

    Reply Author

    Very useful post. thanks you

    does the offest include a +/- ?

    ie if you’re in argentina will it say -10800 and if in Moscow +10800
    or does it just say a flat 10800?

    thanks


  • Veljko Simovic
    Posted on

    Veljko Simovic Veljko Simovic

    Reply Author

    Hello Stanislav,

    i’ve tried your code based on the explanation and all i get is empty page in browser.

    Any help with this?

    Thank you,

    Veljko Simovic


    • Veljko Simovic
      Posted on

      Veljko Simovic Veljko Simovic

      Reply Author

      Update:
      In the code you have on line 5: include(“timezone/timezone.php”);

      But when i open folder timezone there is not timezone.php. I only found these two files:
      test_timezone.php
      make_time_zone_php_code.pl

      What to do next?

      Best regards,

      Veljko


      • Stanislav Khromov
        Posted on

        Stanislav Khromov Stanislav Khromov

        Reply Author

        Hej Veljko,

        Edit 2015-05-11 timezone.php is located in the src/ folder in the latest version of the MaxMind PHP API.

        It appears that you have to compile the time zones from the included Perl script. Once you do that, timezone.php should be generated!


  • Veljko Simovic
    Posted on

    Veljko Simovic Veljko Simovic

    Reply Author

    Hello Stanislav,

    thank you for the reply.

    I wasn’t working in Perl so far, but i will try to find some online guide how to compile it. So i will get back to you if i have some additional question.

    Best regards,

    Veljko Simovic


  • Veljko Simovic
    Posted on

    Veljko Simovic Veljko Simovic

    Reply Author

    Hello Stanislav,

    it tuned out that timezone.php was in src folder. :) This might be useful information for somebody else who downloads this script.

    So i changed the path to inc and two php files, all of them were in src folder and it seems like the script works nice. It gets my local time perfectly. I will still of course test it online.

    Thanks one more time.

    Best regards,

    Veljko


    • Stanislav Khromov
      Posted on

      Stanislav Khromov Stanislav Khromov

      Reply Author

      Hey Veljko,

      Thanks for the comment. Looks like MaxMind have changed the location for some of their files. I have updated the examples to use the new location inside the src/ folder!