-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFreeGeoipService.php
55 lines (47 loc) · 1.38 KB
/
FreeGeoipService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
/**
* Free geo ip service implementation for SilverStripe
*
* @author Tim Klein <tim at dodat dot co dot nz>
* https://github.com/dodat/
* Usage:
* add this to your mysite/_config.php
* Geoip::$default_country_code = FreeGeoipService::get_country_code();
*
* Please note that the free lookup service is restricted to 1000 requests per hour,
* run your own if you need more.
*
* set static $lookup_url to the url of your service
**/
class FreeGeoipService {
static $session_key = "VisitorCountryCode";
static $default_country_code = "NZ";
static $lookup_url = "http://freegeoip.net/";
public static function get_country_code() {
if($code = self::get_country_code_from_session()) {
return $code;
}
$code = self::$default_country_code;
if(isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
$url = self::$lookup_url."json/{$ip}";
if($response = @file_get_contents($url)) {
$data = json_decode($response);
if(Geoip::countryCode2name($data->country_code)) {
$code = $data->country_code;
}
}
}
self::set_country_code_to_session($code);
return $code;
}
function set_country_code_to_session($code) {
Session::set(self::$session_key, $code);
}
function get_country_code_from_session() {
if(!isset($_SESSION)) {
Session::start();
}
return !isset($_GET['flush']) ? Session::get(self::$session_key) : false;
}
}