How To Detect Middle Eastern Users Using PHP

A simple way to determine MENA visitors

We created a simple function by utilizing the popular location and geocoding API provided by HostIP to allow us to easily detect specific users based on location.

A client with ties to political news interests recently came to us requesting that their website display a different image if a user was visiting their website from a country in the Middle East. We created a simple function by utilizing the popular location and geocoding API provided by HostIP to allow us to easily do this. As internet usage in the MENA region continues to riseand smart responsive content campaigns provide an almost-guaranteed return on investment, this function will come in handy if MENA users frequent your website, web application, or publication.

<?phpfunction is_mena($ip = $_SERVER['REMOTE_ADDR']){    /* pull the xml */    $url = 'https://api.hostip.info/?ip='.$ip;    $xml = simplexml_load_file($url);    /* parse the data and store into array */    $citystate = explode(", ", $xml->children('gml', true)->featureMember->children()->Hostip->children('gml', true)->name);    $result['city'] = $citystate[0];    $result['state'] = $citystate[1];    $result['country'] = (array) $xml->children('gml', true)->featureMember->children()->Hostip->countryName;    $result['country'] = $result['country'][0];    $result['country_abbr'] = (array) $xml->children('gml', true)->featureMember->children()->Hostip->countryAbbrev;    $result['country_abbr'] = $result['country_abbr'][0];            return in_array($result['country'], array(    'ALGERIA', 'BAHRAIN', 'EGYPT', 'IRAN', 'IRAQ', 'ISRAEL', 'JORDAN', 'KUWAIT', 'LEBANON', 'LIBYA', 'MOROCCO', 'OMAN', 'PALESTINE', 'QATAR', 'SAUDI ARABIA', 'SYRIA', 'TUNISIA', 'UNITED ARAB EMIRATES', 'YEMEN', 'ARMENIA', 'AZERBAIJAN', 'CYPRUS', 'DJIBOUTI', 'MALTA', 'MAURITANIA', 'SAHRAWI ARAB DEMOCRATIC REPUBLIC', 'SOMALIA', 'SUDAN', 'TURKEY',    ));}

EXAMPLE USAGE:

<?phpif(is_mena()){    echo '<img src="/images/mena_image.png" alt="MENA" />';} else{    echo '<img src="/images/other_image.png" alt="MENA" />';} ?>

Other Recommended Articles

More Bold Blog Reading For Developers, Marketers, and More