-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathApi.php
104 lines (89 loc) · 1.78 KB
/
Api.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
namespace IPInfoDB;
/**
* IPInfoDB API service.
*/
class Api
{
/**
* IPInfoDB API key.
*
* @var string
*/
protected $apiKey;
/**
* Constructor.
*
* @param string $apiKey a IPInfoDB API key
*
* @throws \Exception
*/
public function __construct($apiKey)
{
if (!preg_match('/^[0-9a-z]{64}$/', $apiKey)) {
throw new \Exception(__CLASS__ . ': Invalid IPInfoDB API key.');
}
$this->apiKey = $apiKey;
}
/**
* Get country information by IP address.
*
* @param string $ip
*
* @return array|false
*/
public function getCountry($ip)
{
$response = $this->get('http://api.ipinfodb.com/v3/ip-country?' . http_build_query([
'key' => $this->apiKey,
'format' => 'json',
'ip' => $ip,
]));
if (($json = json_decode($response, true)) === null) {
return false;
}
return $json;
}
/**
* Get city information by IP address.
*
* @param string $ip
*
* @return array|false
*/
public function getCity($ip)
{
$response = $this->get('http://api.ipinfodb.com/v3/ip-city?' . http_build_query([
'key' => $this->apiKey,
'format' => 'json',
'ip' => $ip,
]));
if (($json = json_decode($response, true)) === null) {
return false;
}
return $json;
}
/**
* Call a remote URL using cUrl GET request.
*
* @param string $url
*
* @return string|null
*/
private function get($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
if (!curl_errno($ch)) {
curl_close($ch);
return $response;
}
curl_close($ch);
}
}