ad

Monday, 4 May 2015

Detect user's country and redirect them to a different site or page in PHP

This a simple script that finds user's country based on their IP and shows message or redirects them. This script uses a service called geoPlugin.

This is how you would used it. I have provided with one file, "country_checker_class.php", all this file does it gets users IP and returns message or sends a header back. Now if you scroll down a little you will see an array with couple country names, these are the names that will be allowed to view your website. If a name does not exist in that list, user will be shown a message.

Array
    //***************************************************//
    //Add the countries that are allowed to array.
    //Last item in array will have no comma at the end.
    //***************************************************//
    $countries_allowed = array(
        'United states',
        'united Kingdom',
        'india'
    );


Now if you do not way it to show message but redirect user to a different page, all you have to do is check for the function "show_allowed_or_not()" and at the bottom part where it says return change it to, header("location: your url");  And you're good to go.

Like so:
        function show_allowed_or_not(){
            $ip_address = "90.192.168.54";
            $data = file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip_address);
            $data= unserialize($data);
            $data= strtolower($data['geoplugin_countryName']);

            $result = in_array($data, $this->countries_allowed);
           
            if($result){
                return "Country allowed";
            }else{
                header("location: http://www.google.com");
            }
        }


Finally you should just include the country_checker_class.php" file to your main file(index.php usually) and it's all done!
include("country_checker_class.php");

Download the script:
https://dl.dropboxusercontent.com/u/28490184/webdevtown/country_checker_class.php

No comments:

Post a Comment