Home > Article > Backend Development > PHP determines the city based on the IP address to implement city switching or jump code_PHP tutorial
It is quite simple to obtain the IP address first. The following will introduce two codes for obtaining the IP address. Later, you need to use the QQIP library to find which IP segment the current IP belongs to and then get the city field and return it.
Get IP address
The code is as follows | Copy code | ||||
if ($_SERVER["HTTP_X_FORWARDED_FOR"]) $ip = $_SERVER["HTTP_X_FORWARDED_FOR"]; else if ($_SERVER["HTTP_CLIENT_IP"]) $ip = $_SERVER["HTTP_CLIENT_IP"]; else if ($_SERVER["REMOTE_ADDR "]) $ip = $_SERVER["REMOTE_ADDR"]; else if (getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP"); else if (getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR" ); else $ip = "Unknown"; return $ip; } echo GetIP(); ?>
|
代码如下 | 复制代码 |
function getip () { if (getenv('http_client_ip')) { $ip = getenv('http_client_ip'); } else if (getenv('http_x_forwarded_for')) { $ip = getenv('http_x_forwarded_for'); } else if (getenv('remote_addr')) { $ip = getenv('remote_addr'); } else { $ip = $_server['remote_addr']; } return $ip; |
For more details, please see: http://www.bkjia.com/phper/php/33938.htm
PHP determines the city where the user is located through the IP address
We have obtained the user's IP address above. Next, we will obtain the user's city based on this IP address. Before starting, we need to download a ready-made database QQ IP database.
The latest IP address database: http://8.zjdx2.crsky.com/201209/qqwry0830.rar
How to use: After decompression, QQWry.Dat is the IP address database we want. We create a new ipcity folder and place the database below. The QQ IP database is very convenient to use and the data is very complete. You can follow the official updates in time to keep the data up to date. I highly recommend it:)
Next, we create a new ipaddress.php file in the ipcity directory above and copy it directly. Just enter the following code, and the important places are also commented accordingly. Section B:
The code is as follows | Copy code |
//Determine whether the IP address is valid //explode function decomposes the IP address, and the operation yields an integer result $DataBegin = fread($fd, 4); $useripend = implode('', unpack('L', $DataEnd)); $Middle= intval(($EndNum + $BeginNum) / 2); fseek($fd, $useripbegin + 7 * $Middle); return 'File Error '; //Get the next index after fetching the previous index return 'No Data'; $fd, 1); fclose ($ fd); fseek($fd, $AddrSeek); while(($char = fread($fd, 1)) != chr(0)) $useripFlag = fread($fd, 1); //返回IP地址对应的城市结果 return $useripaddr; |
PHP根据IP地址实现城市切换或跳转
到这里,其实问题已经很简单了,用简单的js就通通搞定。C段如下:
//根据IP地址跳转指定页面js取得城市
代码如下
|
复制代码
|
||||||||||||||||
|