I don’t know if you need to obtain the real-time location of users when developing some projects. Especially for some large websites, it is very important for the website to obtain the user’s local information. These websites are very important to users. When accessing, it will judge the information of the user's location by itself, and then jump to the corresponding sub-site. This gives the user a good experience, rather than all users from all over the country. Come and visit Beijing Station or Shanghai Station.
Using PHP to obtain the location of visitors is widely used in large sites. Today, the editor will lead you to create such a small function. Of course, you must first consider using a third-party IP interface. At present, the larger IP interfaces include Taobao, Sina, Net
, QQ, etc. Finally, I chose the API where Sina IP belongs. It is also very simple to use. Obtain the IP address, use the Sina interface, return a status code, and then obtain the user's location based on the status code, and then make a judgment to display different content in each region.
The PHP code is as follows: <?php
$ip = "218.192.3.42";
$json = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip);
$json = json_decode($json, true);
echo "IP地址:".$ip;//www.php.cn
echo "归属地:".$json["country"].$json["province"].$json["city"].$json["district"].$json["isp"];
?>
<script type="text/javascript" src="http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js" charset="utf-8"></script>
<script type="text/javascript">
alert(remote_ip_info.country+" "+remote_ip_info.city);
</script>
<?php
$ip = $_SERVER["REMOTE_ADDR"];
$json = file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip);
$json = json_decode($json, true);
if($json["province"]=="安徽"){
echo "document.writeln(\"安徽");\n";
}//www.php.cn
if($json["province"]=="河南"){
echo "document.writeln(\"河南");\n";
}
?>
<script type="text/javascript" src="ip.php?action=test"></script>
action is the passed parameter, which can be deleted if it is not used.