This article mainly shares with you how to obtain the user IP address in PHP, how PHP judges the user's city based on the IP address, and how PHP switches or redirects the city based on the IP address. Let's take a look at some common code.
PHP
<? Phpinclude_once ('./qqwry. php'); $ QQWry = new QQWry; function get_real_ip () {$ ip = false; if (! Empty ($ _ SERVER ["HTTP_CLIENT_IP"]) {$ ip = $ _ SERVER ["HTTP_CLIENT_IP"];} if (! Empty ($ _ SERVER ['http _ X_FORWARDED_FOR ']) {$ ips = explode (",", $ _ SERVER ['http _ X_FORWARDED_FOR']); if ($ ip) {array_unshift ($ ips, $ ip); $ ip = FALSE;} for ($ I = 0; $ I <count ($ ips ); $ I ++) {if (! Eregi ("^ (10 | 172 \. 16 | 192 \. (168 )\. ", $ ips [$ I]) {$ ip = $ ips [$ I]; break ;}} return $ ip;} function is_ip ($ str) {$ ip = explode (". ", $ str); if (count ($ ip) <4 | count ($ ip)> 4) return 0; foreach ($ ip as $ ip_addr) {if (! Is_numeric ($ ip_addr) return 0; if ($ ip_addr <0 | $ ip_addr> 255) return 0;} return 1 ;} $ ip = $ _ SERVER ['remote _ ADDR ']; $ ifErr = $ QQWry-> QQWry ($ ip); $ city = $ QQWry-> Country. $ QQWry-> Local; // echo $ city; */if (strpos ($ city, 'region region ')! = False) {$ city = "Hangzhou district";} else if (strpos ($ city, 'xianline ')! = False) {$ city = "Xianlin";} else if (strpos ($ city, 'qinhuai region ')! = False) {$ city = "Qinhuai District";} else if (strpos ($ city, 'jiangning ')! = False) {$ city = "Jiangning";} else if (strpos ($ city, 'gulou ')! = False) {$ city = "Gulou";} else {$ city = "Qixia";} if (isset ($ _ GET ['chengshi ']) {// ********************************* setcookie ("cookie_city ", $ _ GET ['chengshi '], time () + 3600*24); $ city = $ _ GET ['chengshi'];} else if (isset ($ _ COOKIE ["cookie_city"]) {// ¼ ² â Ç çen'~~úço ~~~cookie $ city =$ _ Cookie ["cookie_city"]; // Please specify your own Cookie + £' your µäê ý ¾} else {setcookie ("cookie_city", $ city, time () + 3600*24 ); // '{}}}}» {'{± äá{$ _ COO KIE ["cookie_city"] = $ city;}?>
HTML