php获取当前用户所在城市
php通过ip免申请api获取所在城市的代码包括省市区sql数据
<?php
function getName($pinyin,$lv){
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "ttx";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "连接数据库成功";exit;
} catch(PDOException $e) {
echo "连接数据库失败: " . $e->getMessage();exit;
}
// 层级(0:国家;1:省;2:市;3:区)
$sql = "SELECT * from cg_gym_city_info where pinyin='{$pinyin}' and level_type ={$lv}";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return isset($result['name'])?$result['name']:"";
}
if($_GET['ip']){
$ip = $_GET['ip'];
}else{
$ip = $_SERVER['REMOTE_ADDR'];
}
$url = "http://ip-api.io/json/{$ip}";
$response = file_get_contents($url);
$data = json_decode($response, true);
$region = $data['region_name'];
$city = $data['city'];
$data['regionCNName']=getName($region,1);
$data['cityCNName']=getName($city,2);
var_dump($data);exit;
文章来源:https://www.toymoban.com/news/detail-559762.html
文章来源地址https://www.toymoban.com/news/detail-559762.html
到了这里,关于php通过IP获取用户当前所在城市的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!