-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlookup.php
49 lines (38 loc) · 1.11 KB
/
lookup.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
<?php
include 'config.php';
// get the json from the post request
$ip = file_get_contents('php://input');
// if it's empty, stop it
if (empty($ip)) {
echo "Empty ip, stop it.";
die();
}
// Create connection
$conn = new mysqli($db_host, $db_user, $db_password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Connection failed";
}
// escape the ip sql injection
$ip = $conn->real_escape_string($ip);
// save it to the database
$sql = "SELECT * FROM `geohopper`.`ip_cache` WHERE `ip` = '$ip';";
$result = $conn->query($sql);
// get the json from the database
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$json = $row["json"];
echo $json;
} else {
// get the json from the ipinfo api
$json = file_get_contents("http://ipinfo.io/$ip/json?token=$ipinfo_token");
echo $json;
// get unix timestamp
$timestamp = time();
// save it to the database
$sql = "INSERT INTO `geohopper`.`ip_cache` (`ip`, `json`, `timestamp`) VALUES ('$ip', '$json', '$timestamp');";
$result = $conn->query($sql);
}
?>