Php implements how to obtain the province and city based on the IP address. Php implements how to obtain the province and city based on the IP address. today, this article discusses how to obtain the user IP address in PHP, how to determine the user's city based on the IP address, and how to obtain the province and city based on the IP address of PHP.
Today, we will discuss how to obtain the IP address of a user in PHP, how PHP judges the city where the user is located based on the IP address, and how PHP switches or redirects the city based on the IP address.
How to obtain the geographic location (province, city, etc.) based on the existing IP address
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Function GetIpLookup ($ ip = ''){ If (empty ($ ip )){ Return 'Enter the IP address '; } $ Res = @ file_get_contents ('http: // int.dpool.sina.com.cn/iplookup/iplookup.php? Format = js & ip = '. $ ip ); If (empty ($ res) {return false ;} $ JsonMatches = array (); Preg_match ('# {. + ?} # ', $ Res, $ jsonMatches ); If (! Isset ($ jsonMatches [0]) {return false ;} $ Json = json_decode ($ jsonMatches [0], true ); If (isset ($ json ['ret ']) & $ json ['ret'] = 1 ){ $ Json ['IP'] = $ ip; Unset ($ json ['ret ']); } Else { Return false; } Return $ json; } $ IpInfos = GetIpLookup ('192. 125.114.144 '); // baidu.com IP address Var_dump ($ ipInfos ); |
Release a simplified version
?
1 2 3 4 5 6 7 |
Function getIpAddress (){ $ IpContent = file_get_contents ("http://int.dpool.sina.com.cn/iplookup/iplookup.php? Format = js "); $ JsonData = explode ("=", $ ipContent ); $ JsonAddress = substr ($ jsonData [1], 0,-1 ); Return $ jsonAddress; } $ Ip_info = json_decode (getIpAddress ()); |
PHP implements City switching or redirection based on IP addresses
Here, the problem is actually quite simple. it can be done with simple js. Section C is as follows:
// Jump to the specified page based on the IP address. js gets the city
Var city = ''; // jump to the specified page according to the IP address of all cities
If (city. indexOf ("Shanghai")> = 0 ){
Window. location. href = "http://shanghai.demo.com /";}
Place the-segment code and the C-segment code above in the header and end of the B-segment code respectively, and then add the following code on the page to jump:
Is refreshing the page as expected?
The above is all the content of this article. I hope you will like it.
Today, I will discuss how to obtain the user IP address in PHP, determine the user's city based on the IP address in PHP, and implement city switch based on the IP address in PHP...