search
HomeBackend DevelopmentPHP TutorialHow to get user IP address in PHP

This article mainly shares with you how to obtain the user's IP address in PHP, PHP determines the city where the user is located based on the IP, and PHP implements city switching or jump based on the IP.

Let’s first look at the codes that are commonly used by individuals

PHP

<?php
include_once(&#39;./qqwry.php&#39;);
$QQWry=new QQWry; 
 
function get_real_ip(){
$ip=false;
if(!empty($_SERVER["HTTP_CLIENT_IP"])){
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
if (!empty($_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;])) {
$ips = explode (", ", $_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;]);
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[&#39;REMOTE_ADDR&#39;]; 
$ifErr=$QQWry->QQWry($ip); 
$city = $QQWry->Country.$QQWry->Local;
 
//echo $city;*/
 
 
if (strpos($city,&#39;玄武区&#39;)!==false){
  $city = "玄武区";
}
else if(strpos($city,&#39;仙林&#39;)!==false){
  $city = "仙林";
}
else if(strpos($city,&#39;秦淮区&#39;)!==false){
  $city = "秦淮区";
}
else if(strpos($city,&#39;江宁&#39;)!==false){
  $city = "江宁";
}
else if(strpos($city,&#39;鼓楼&#39;)!==false){
  $city = "鼓楼";
}
else{
  $city = "栖霞";
}
if (isset($_GET[&#39;chengshi&#39;])) { //Ê×Ïȼì²âÊÇ·ñ»ñµÃÁË GET ´«µÝµÄÊý¾Ý  
setcookie("cookie_city",$_GET[&#39;chengshi&#39;],time()+3600*24);
$city = $_GET[&#39;chengshi&#39;]; 
} 
else if (isset($_COOKIE["cookie_city"])) { //¼ì²âÊÇ·ñ´æÔÚêdzÆCookie  
$city = $_COOKIE["cookie_city"]; //ÏÔʾCookie±£´æµÄÊý¾Ý 
} 
else {  
setcookie("cookie_city",$city,time()+3600*24); //´¿³õʼ»¯´Ë±äÁ¿ 
$_COOKIE["cookie_city"] = $city;
} 
?>

HTML

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8"/>
<LINK href="css/css.css" type=text/css rel=stylesheet>
<SCRIPT src="js/jquery-1.4.2.min.js" type=text/javascript></SCRIPT>
<title>城市切换</title>
</head>
<BODY>
<p class=selCity id=allCity style="DISPLAY: none">
<p class=area>
<TABLE>
 <TBODY>
 <TR>
  <TD><A class=cur href="show.html">玄武区</A></TD>
  <TD><A href="show1.html">仙林</A></TD>
  <TD><A href="show2.html">秦淮区</A></TD>
  <TD><A href="show3.html">鼓楼</A></TD>
  <TD><A href="show4.html">江宁</A></TD>
  <TD><A href="show5.html">栖霞区</A></TD>
 </TR>
 </TBODY></TABLE>
<p class=none><A id=foldin href="javascript:;">全部</A></p></p></p>
<p class=header>
  <p class=area>
    <p class=r>
      <p class="topCtiy clear">
        <UL>
         
        <LI class=i1><A href="index.php">全部小区</A></LI>
         
         <LI class=i1>
         <?php 
         echo $city; 
         ?>
         </LI>
         <LI class=i2 id=changeCity>切换城市</LI>
        </UL>
      </p>
    </p>
  </p>
</p>
<SCRIPT type=text/javascript>
jQuery(function(){
  $("#changeCity").click(function(a){
    $("#allCity").slideDown(300);
    a.stopPropagation();
    $(this).blur();
  });
  $("#allCity").click(function(a){
    a.stopPropagation()
  });
  $(document).click(function(a){
    a.button!=2 && $("#allCity").slideUp(300)
  });
  $("#foldin").click(function(){
    $("#allCity").slideUp(300)
  });
});
</SCRIPT>
</body>
</html>

In addition, the implementation method of netizens is attached:

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 , just copy the following code into it, and the important places are also commented accordingly. Section B:

<?
/*
函数名称:ipCity
参数说明:$userip——用户IP地址
函数功能:PHP通过IP地址判断用户所在城市
author:lee
contact:xpsem2010@gmail.com
*/
function ipCity($userip) {
  //IP数据库路径,这里用的是QQ IP数据库 20110405 纯真版
  $dat_path = &#39;QQWry.dat&#39;;
  //判断IP地址是否有效
  if(!ereg("^([0-9]{1,3}.){3}[0-9]{1,3}$", $userip)){
    return &#39;IP Address Invalid&#39;;
  }
  //打开IP数据库
  if(!$fd = @fopen($dat_path, &#39;rb&#39;)){
    return &#39;IP data file not exists or access denied&#39;;
  }
  //explode函数分解IP地址,运算得出整数形结果
  $userip = explode(&#39;.&#39;, $userip);
  $useripNum = $userip[0] * 16777216 + $userip[1] * 65536 + $userip[2] * 256 + $userip[3];
  //获取IP地址索引开始和结束位置
  $DataBegin = fread($fd, 4);
  $DataEnd = fread($fd, 4);
  $useripbegin = implode(&#39;&#39;, unpack(&#39;L&#39;, $DataBegin));
  if($useripbegin < 0) $useripbegin += pow(2, 32);
  $useripend = implode(&#39;&#39;, unpack(&#39;L&#39;, $DataEnd));
  if($useripend < 0) $useripend += pow(2, 32);
  $useripAllNum = ($useripend - $useripbegin) / 7 + 1;
  $BeginNum = 0;
  $EndNum = $useripAllNum;
  //使用二分查找法从索引记录中搜索匹配的IP地址记录
  while($userip1num>$useripNum || $userip2num<$useripNum) {
    $Middle= intval(($EndNum + $BeginNum) / 2);
    //偏移指针到索引位置读取4个字节
    fseek($fd, $useripbegin + 7 * $Middle);
    $useripData1 = fread($fd, 4);
    if(strlen($useripData1) < 4) {
      fclose($fd);
      return &#39;File Error&#39;;
    }
    //提取出来的数据转换成长整形,如果数据是负数则加上2的32次幂
    $userip1num = implode(&#39;&#39;, unpack(&#39;L&#39;, $useripData1));
    if($userip1num < 0) $userip1num += pow(2, 32);
    //提取的长整型数大于我们IP地址则修改结束位置进行下一次循环
    if($userip1num > $useripNum) {
      $EndNum = $Middle;
      continue;
    }
    //取完上一个索引后取下一个索引
    $DataSeek = fread($fd, 3);
    if(strlen($DataSeek) < 3) {
      fclose($fd);
      return &#39;File Error&#39;;
    }
    $DataSeek = implode(&#39;&#39;, unpack(&#39;L&#39;, $DataSeek.chr(0)));
    fseek($fd, $DataSeek);
    $useripData2 = fread($fd, 4);
    if(strlen($useripData2) < 4) {
      fclose($fd);
      return &#39;File Error&#39;;
    }
    $userip2num = implode(&#39;&#39;, unpack(&#39;L&#39;, $useripData2));
    if($userip2num < 0) $userip2num += pow(2, 32);
    //找不到IP地址对应城市
    if($userip2num < $useripNum) {
      if($Middle == $BeginNum) {
        fclose($fd);
        return &#39;No Data&#39;;
      }
      $BeginNum = $Middle;
    }
  }
  $useripFlag = fread($fd, 1);
  if($useripFlag == chr(1)) {
    $useripSeek = fread($fd, 3);
    if(strlen($useripSeek) < 3) {
      fclose($fd);
      return &#39;System Error&#39;;
    }
    $useripSeek = implode(&#39;&#39;, unpack(&#39;L&#39;, $useripSeek.chr(0)));
    fseek($fd, $useripSeek);
    $useripFlag = fread($fd, 1);
  }
  if($useripFlag == chr(2)) {
    $AddrSeek = fread($fd, 3);
    if(strlen($AddrSeek) < 3) {
      fclose($fd);
      return &#39;System Error&#39;;
    }
    $useripFlag = fread($fd, 1);
    if($useripFlag == chr(2)) {
      $AddrSeek2 = fread($fd, 3);
      if(strlen($AddrSeek2) < 3) {
        fclose($fd);
        return &#39;System Error&#39;;
      }
      $AddrSeek2 = implode(&#39;&#39;, unpack(&#39;L&#39;, $AddrSeek2.chr(0)));
      fseek($fd, $AddrSeek2);
    } else {
      fseek($fd, -1, SEEK_CUR);
    }
    while(($char = fread($fd, 1)) != chr(0))
      $useripAddr2 .= $char;
    $AddrSeek = implode(&#39;&#39;, unpack(&#39;L&#39;, $AddrSeek.chr(0)));
    fseek($fd, $AddrSeek);
    while(($char = fread($fd, 1)) != chr(0))
      $useripAddr1 .= $char;
  } else {
    fseek($fd, -1, SEEK_CUR);
    while(($char = fread($fd, 1)) != chr(0))
      $useripAddr1 .= $char;
    $useripFlag = fread($fd, 1);
    if($useripFlag == chr(2)) {
      $AddrSeek2 = fread($fd, 3);
      if(strlen($AddrSeek2) < 3) {
        fclose($fd);
        return &#39;System Error&#39;;
      }
      $AddrSeek2 = implode(&#39;&#39;, unpack(&#39;L&#39;, $AddrSeek2.chr(0)));
      fseek($fd, $AddrSeek2);
    } else {
      fseek($fd, -1, SEEK_CUR);
    }
    while(($char = fread($fd, 1)) != chr(0)){
      $useripAddr2 .= $char;
    }
  }
  fclose($fd);
  //返回IP地址对应的城市结果
  if(preg_match(&#39;/http/i&#39;, $useripAddr2)) {
    $useripAddr2 = &#39;&#39;;
  }
  $useripaddr = "$useripAddr1 $useripAddr2";
  $useripaddr = preg_replace(&#39;/CZ88.Net/is&#39;, &#39;&#39;, $useripaddr);
  $useripaddr = preg_replace(&#39;/^s*/is&#39;, &#39;&#39;, $useripaddr);
  $useripaddr = preg_replace(&#39;/s*$/is&#39;, &#39;&#39;, $useripaddr);
  if(preg_match(&#39;/http/i&#39;, $useripaddr) || $useripaddr == &#39;&#39;) {
    $useripaddr = &#39;No Data&#39;;
  }
  return $useripaddr;
}
?>

PHP realizes city switching or jumping based on IP address

At this point, the problem is actually very simple. It can be solved with simple js. Section C is as follows:

//根据IP地址跳转指定页面js取得城市
var city=&#39;<?echo ipCity($xp_UserIp);?>&#39;;
//根据IP地址所有城市跳转到指定页面
if(city.indexOf("上海市")>=0){
    window.location.href="http://shanghai.demo.com/";
}

Place the beginning A section code and the above C section code at the beginning and end of the B section code respectively, and then we add the following code to the page that needs to be jumped:

Refresh the page, does it achieve the desired effect? Woolen cloth?

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Detailed explanation of how PHP implements parsing and generating xml based on DOMDocument

PHP implements based on XMLWriter's method of operating xml

PHP's method of adding, deleting, modifying and checking the tool class based on the object-oriented mysqli extension library

The above is the detailed content of How to get user IP address in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools