1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* File: GeoIP.php |
4
|
|
|
* Category: - |
5
|
|
|
* Author: M. Goldenbaum |
6
|
|
|
* Created: 17.10.20 23:21 |
7
|
|
|
* Updated: - |
8
|
|
|
* |
9
|
|
|
* Description: |
10
|
|
|
* - |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace Webklex\GeoIP; |
14
|
|
|
|
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Class GeoIP |
18
|
|
|
* |
19
|
|
|
* @package Webklex\PHPIMAP |
20
|
|
|
*/ |
21
|
|
|
class GeoIP { |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Api endpoint |
25
|
|
|
* @var string $endpoint |
26
|
|
|
*/ |
27
|
|
|
protected $endpoint = "https://www.gogeoip.com"; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Session cache holder |
31
|
|
|
* @var array $cache |
32
|
|
|
*/ |
33
|
|
|
protected $cache = []; |
34
|
|
|
|
35
|
|
|
/** @var RemoteAddress $remote_address*/ |
36
|
|
|
protected $remote_address; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* GeoIP constructor. |
40
|
|
|
* @param string $endpoint |
41
|
|
|
*/ |
42
|
|
|
public function __construct($endpoint = null) { |
43
|
|
|
if ($endpoint !== null) { |
44
|
|
|
$this->endpoint = $endpoint; |
45
|
|
|
} |
46
|
|
|
$this->remote_address = new RemoteAddress(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Get the geoip information for the current ip |
51
|
|
|
* |
52
|
|
|
* @return array|null |
53
|
|
|
*/ |
54
|
|
|
public function current(){ |
55
|
|
|
return $this->get($this->remote_address->getIpAddress()); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Get geoip information for a given ip |
60
|
|
|
* @param string $ip |
61
|
|
|
* |
62
|
|
|
* @return array|null |
63
|
|
|
*/ |
64
|
|
|
public function get($ip){ |
65
|
|
|
if (isset($this->cache[$ip])) { |
66
|
|
|
return $this->cache[$ip]; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $this->cache[$ip] = $this->call($ip); |
|
|
|
|
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Call the api and parse the response |
75
|
|
|
* @param string $ip |
76
|
|
|
* @param string $type |
77
|
|
|
* @param integer $retries |
78
|
|
|
* |
79
|
|
|
* @return array|boolean |
80
|
|
|
*/ |
81
|
|
|
protected function call($ip, $type = 'json', $retries = 3) { |
82
|
|
|
do { |
83
|
|
|
$ch = curl_init(); |
84
|
|
|
|
85
|
|
|
curl_setopt($ch, CURLOPT_URL, $this->endpoint.'/'.$type.'/'.$ip); |
|
|
|
|
86
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
87
|
|
|
|
88
|
|
|
$output = curl_exec($ch); |
|
|
|
|
89
|
|
|
curl_close($ch); |
|
|
|
|
90
|
|
|
|
91
|
|
|
if($output == false) { |
|
|
|
|
92
|
|
|
sleep(1); |
93
|
|
|
}else{ |
94
|
|
|
return json_decode($output, true); |
|
|
|
|
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
$retries++; |
98
|
|
|
} |
99
|
|
|
while($retries > 0); |
100
|
|
|
|
101
|
|
|
return null; |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|