Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Setup maxmind HTTP service endpoint
- define('MAXMIND_SERVICE_URI', 'http://skyspacex.com:3001');
- define('MAXMIND_REQUEST_TIMEOUT_MS', 500);
- /**
- * Check if current request IP address belongs to specified country ISO code.
- *
- * @param $isoCode
- * @return bool
- */
- function isCountry($isoCode)
- {
- try {
- // NOTICE! Getting IP address from GET params is unsafe! So, this is for test ONLY!
- if (!empty($_GET['ip']) && filter_var($_GET['ip'], FILTER_VALIDATE_IP)) {
- $ip = $_GET['ip'];
- } else if (!empty($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
- $ip = $_SERVER['HTTP_CLIENT_IP'];
- } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
- $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
- } else {
- $ip = $_SERVER['REMOTE_ADDR'];
- }
- if (!extension_loaded('curl')) {
- throw new Exception('Curl extension is not installed');
- }
- $ch = curl_init(MAXMIND_SERVICE_URI . "?ip=$ip");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
- curl_setopt($ch, CURLOPT_TIMEOUT_MS, MAXMIND_REQUEST_TIMEOUT_MS);
- $response = curl_exec($ch);
- $curl_errno = curl_errno($ch);
- $curl_error = curl_error($ch);
- curl_close($ch);
- if ($curl_errno > 0) {
- throw new Exception("Curl error ($curl_errno): $curl_error");
- }
- $data = json_decode($response, true);
- if (!$data) {
- throw new Exception('Invalid json response from server');
- }
- if ($data['Error']) {
- throw new Exception("Data error: {$data['Error']}");
- }
- if (!$data['Data'] || !is_array($data['Data']) || !array_key_exists('Country', $data['Data'])) {
- throw new Exception('No country data');
- }
- return $data['Data']['Country']['IsoCode'] === $isoCode;
- } catch (Exception $e) {
- // @TODO log error message
- //echo "Something went wrong on ip detection: {$e->getMessage()}";
- return false;
- }
- }
- // Usage.
- if (isCountry('UA')) {
- echo "Received request from Ukraine";
- // Paste your JS script here
- } else {
- echo "Request outsie Ukraine.";
- // Here will works common ad's.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement