Home Backend Development PHP Tutorial PHP implements multi-city switching special effects_php skills

PHP implements multi-city switching special effects_php skills

May 16, 2016 pm 08:08 PM

Let’s first take a look at the codes that are commonly used by individuals
PHP
<&#63;php



include_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,'玄武区')!==false){
  $city = "玄武区";
}
else if(strpos($city,'仙林')!==false){
  $city = "仙林";
}
else if(strpos($city,'秦淮区')!==false){
  $city = "秦淮区";
}
else if(strpos($city,'江宁')!==false){
  $city = "江宁";
}
else if(strpos($city,'鼓楼')!==false){
  $city = "鼓楼";
}
else{
  $city = "栖霞";
}



if (isset($_GET['chengshi'])) { //&Ecirc;×&Iuml;&Egrave;&frac14;ì&sup2;&acirc;&Ecirc;&Ccedil;·&ntilde;&raquo;&ntilde;&micro;&Atilde;&Aacute;&Euml; GET &acute;&laquo;&micro;&Yacute;&micro;&Auml;&Ecirc;&yacute;&frac34;&Yacute;  
setcookie("cookie_city",$_GET['chengshi'],time()+3600*24);
$city = $_GET['chengshi']; 
} 
else if (isset($_COOKIE["cookie_city"])) { //&frac14;ì&sup2;&acirc;&Ecirc;&Ccedil;·&ntilde;&acute;&aelig;&Ocirc;&Uacute;ê&Ccedil;&sup3;&AElig;Cookie  
$city = $_COOKIE["cookie_city"]; //&Iuml;&Ocirc;&Ecirc;&frac34;Cookie±&pound;&acute;&aelig;&micro;&Auml;&Ecirc;&yacute;&frac34;&Yacute; 
} 
else {  
setcookie("cookie_city",$city,time()+3600*24); //&acute;&iquest;&sup3;&otilde;&Ecirc;&frac14;&raquo;&macr;&acute;&Euml;±&auml;&Aacute;&iquest; 
$_COOKIE["cookie_city"] = $city;
} 
&#63;>
Copy after login
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>
<DIV class=selCity id=allCity style="DISPLAY: none">
<DIV 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>
<DIV class=none><A id=foldin href="javascript:;">全部</A></DIV></DIV></DIV>
<DIV class=header>
  <DIV class=area>
    <DIV class=r>
      <DIV class="topCtiy clear">
        <UL>
         
        <LI class=i1><A href="index.php">全部小区</A></LI>
         
         <LI class=i1>
         <&#63;php 
         echo $city; 
         &#63;>
         </LI>
         <LI class=i2 id=changeCity>切换城市</LI>
        </UL>
      </DIV>
    </DIV>
  </DIV>
</DIV>
<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>
Copy after login
Attached is also the implementation method from netizens:
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 easy 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 just copy the following code into it. The important places are also commented accordingly. Section B:
<&#63;
/*
函数名称:ipCity
参数说明:$userip——用户IP地址
函数功能:PHP通过IP地址判断用户所在城市
author:lee
contact:xpsem2010@gmail.com
*/
function ipCity($userip) {
  //IP数据库路径,这里用的是QQ IP数据库 20110405 纯真版
  $dat_path = 'QQWry.dat';



  //判断IP地址是否有效
  if(!ereg("^([0-9]{1,3}.){3}[0-9]{1,3}$", $userip)){
    return 'IP Address Invalid';
  }



  //打开IP数据库
  if(!$fd = @fopen($dat_path, 'rb')){
    return 'IP data file not exists or access denied';
  }



  //explode函数分解IP地址,运算得出整数形结果
  $userip = explode('.', $userip);
  $useripNum = $userip[0] * 16777216 + $userip[1] * 65536 + $userip[2] * 256 + $userip[3];



  //获取IP地址索引开始和结束位置
  $DataBegin = fread($fd, 4);
  $DataEnd = fread($fd, 4);
  $useripbegin = implode('', unpack('L', $DataBegin));
  if($useripbegin < 0) $useripbegin += pow(2, 32);
  $useripend = implode('', unpack('L', $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 'File Error';
    }
    //提取出来的数据转换成长整形,如果数据是负数则加上2的32次幂
    $userip1num = implode('', unpack('L', $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 'File Error';
    }
    $DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
    fseek($fd, $DataSeek);
    $useripData2 = fread($fd, 4);
    if(strlen($useripData2) < 4) {
      fclose($fd);
      return 'File Error';
    }
    $userip2num = implode('', unpack('L', $useripData2));
    if($userip2num < 0) $userip2num += pow(2, 32);



    //找不到IP地址对应城市
    if($userip2num < $useripNum) {
      if($Middle == $BeginNum) {
        fclose($fd);
        return 'No Data';
      }
      $BeginNum = $Middle;
    }
  }



  $useripFlag = fread($fd, 1);
  if($useripFlag == chr(1)) {
    $useripSeek = fread($fd, 3);
    if(strlen($useripSeek) < 3) {
      fclose($fd);
      return 'System Error';
    }
    $useripSeek = implode('', unpack('L', $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 'System Error';
    }
    $useripFlag = fread($fd, 1);
    if($useripFlag == chr(2)) {
      $AddrSeek2 = fread($fd, 3);
      if(strlen($AddrSeek2) < 3) {
        fclose($fd);
        return 'System Error';
      }
      $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
      fseek($fd, $AddrSeek2);
    } else {
      fseek($fd, -1, SEEK_CUR);
    }



    while(($char = fread($fd, 1)) != chr(0))
      $useripAddr2 .= $char;



    $AddrSeek = implode('', unpack('L', $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 'System Error';
      }
      $AddrSeek2 = implode('', unpack('L', $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('/http/i', $useripAddr2)) {
    $useripAddr2 = '';
  }
  $useripaddr = "$useripAddr1 $useripAddr2";
  $useripaddr = preg_replace('/CZ88.Net/is', '', $useripaddr);
  $useripaddr = preg_replace('/^s*/is', '', $useripaddr);
  $useripaddr = preg_replace('/s*$/is', '', $useripaddr);
  if(preg_match('/http/i', $useripaddr) || $useripaddr == '') {
    $useripaddr = 'No Data';
  }



  return $useripaddr;
}
&#63;>
Copy after login
PHP implements city switching or jump based on IP address
At this point, the problem is actually very simple. It can be solved with simple js. Paragraph C is as follows:
//根据IP地址跳转指定页面js取得城市
var city='<&#63;echo ipCity($xp_UserIp);&#63;>';

//根据IP地址所有城市跳转到指定页面
if(city.indexOf("上海市")>=0){
    window.location.href="http://shanghai.demo.com/";
}
Copy after login
Place the beginning A segment of code and the above C segment of code at the beginning and end of the B segment of 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?
The above is a detailed introduction to PHP obtaining IP address, PHP judging city based on IP address, and PHP implementing city switching or jumping based on IP address. In fact, automatic city switching through IP address in PHP is a typical application of this method. . By analogy, we can also block user access from specified IP addresses or cities through this method. Do your own research, it’s quite simple:)
Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles