PHP在线IP地址查询

ip.cn为例,根据IP地址在线查询省市区

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
<?php
$url='https://ip.cn/index.php?ip=8.8.8.8';

$data["country"] = 'unknown';
$data["region"] = 'unknown';
$data["city"] = 'unknown';

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT ,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.113 Safari/537.36");
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$html = curl_exec($ch);

if (preg_match_all('%<p.*?>(.*?)</p>%si', $html, $matches)) {
$arr[0][] = $matches[1];
}
if ($arr[0][0][2] && strpos($arr[0][0][2], 'GeoIP') !== FALSE) {
$geoip = str_replace("GeoIP:", "", $arr[0][0][2]);
$geo_arr = explode(",", $geoip);
if (count($geo_arr) == 3) {
$data['country'] = trim($geo_arr[2]);
$data['region'] = trim($geo_arr[1]);
$data['city'] = trim($geo_arr[0]);
}
if (count($geo_arr) == 1) {
$data['country'] = trim($geo_arr[0]);
}
if (count($geo_arr) == 2) {
$data['country'] = trim($geo_arr[1]);
$data['region'] = trim($geo_arr[0]);
}
} else if ($arr[0][0][3] && strpos($arr[0][0][3], 'GeoIP') !== FALSE) { //过滤广告
$geoip = str_replace("GeoIP:", "", $arr[0][0][3]);
$geo_arr = explode(",",$geoip);
if (count($geo_arr) == 3) {
$data['country'] = trim($geo_arr[2]);
$data['region'] = trim($geo_arr[1]);
$data['city'] = trim($geo_arr[0]);
}
if (count($geo_arr) == 1) {
$data['country'] = trim($geo_arr[0]);
}
if (count($geo_arr) == 2) {
$data['country'] = trim($geo_arr[1]);
$data['region'] = trim($geo_arr[0]);
}
}

var_dump($data);
?>

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :