获取手机号码归属地及运营商信息

Posted by Nathan on 2018-12-07
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
/**
* 手机号码归属地查询
* @param $tel
* @return string
*/
function getLocation($tel)
{
// 过滤参数
if ( !isPhoneNumber($tel) ) return ['code'=>200,'status'=>false,'msg'=>'Cell phone number error!'];

// 请求地址
$url = 'http://mobsec-dianhua.baidu.com/dianhua_api/open/location?tel='.$tel;

// 发起请求
//$res = file_get_contents($url);
$res = curlRequest($url,'','GET');

if ( $res['code'] !== 200 ) return ['code'=>$res['code'],'status'=>false,'msg'=>$res['responseHeader']['msg']];// 判断请求是否成功

$data = $res['response'][$tel];// 接收返回值

if ( !$data ) return ['code'=>200,'status'=>false,'msg'=>'API Exception!'];// 返回值为空

$response['province'] = $data['detail']['province']; // 归属地
$response['city'] = $data['detail']['area'][0]['city']; // 城市
$response['service'] = $data['detail']['operator']; // 运行商
$response['fullname'] = $data['location']; // 运行商全称

return ['code'=>200,'status'=>true,'data'=>$response];
}

/**
* 手机号码格式验证
* @param $tel
* @return bool
*/
function isPhoneNumber($tel)//手机号码正则表达试
{
return (preg_match("/0?(13|14|15|17|18|19)[0-9]{9}/",$tel))?true:false;
}

/**
* 发起CURL请求
* @param string $url 请求地址
* @param string $data 请求数据
* @param string $method 请求方式
* @return array 一维数组
*/
function curlRequest($url,$data = '',$method = 'POST')
{
$ch = curl_init(); //初始化CURL句柄
curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而s不是直接输出
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式

curl_setopt($ch,CURLOPT_HTTPHEADER,array("X-HTTP-Method-Override: $method"));//设置HTTP头信息
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
$document = curl_exec($ch);//执行预定义的CURL
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE); //获取HTTP请求状态码~
curl_close($ch);

$document = json_decode(removeBOM($document),true);
$document['code'] = $code;

return $document;
}

/**
* 检测并移除 BOM 头
* @param string $str 字符串
* @return string 去除BOM以后的字符串
*/
function removeBOM($str = '')
{
if (substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) {
$str = substr($str, 3);
}
return $str;
}

echo "<pre>";
var_dump( getLocation('18888888888') );exit();