Home >Backend Development >PHP Tutorial >Example of creating abnormal login IP detection function using PHP

Example of creating abnormal login IP detection function using PHP

墨辰丷
墨辰丷Original
2018-05-30 17:45:591783browse

This article mainly introduces the example of creating abnormal login IP detection function in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

Use function query database traversal implementation

/**
 * 不在常用ip地址登录返回描红信息
 * @param string $ip  ip地址
 * @param string $name  用户名
 * @return string
 */

function errorIp($ip,$name){

  $nowip = get_client_ip();
  //判断ip和当前ip是否相同,不同则查询数据库对比
  if($ip == $nowip ){
    //相同直接返回字符串
    $str = &#39;<font color="blue"&#39;.">登录IP:".$ip."</font>";
  }else{
    //不同则记数这个ip地址数量
    $count =  M(&#39;log&#39;)->where("name=&#39;{$name}&#39; AND ip=&#39;{$ip}&#39;")->count();
    //如果超过一定数量则是正常ip否则为异常返回字符串
    if($count > 10){
      $str = &#39;<font color="blue"&#39;.">登录IP:".$ip."</font>";
    }else{
      $str = &#39;<font color="red"&#39;.">异常IP:".$ip."</font>";
    }
  }

  return $str;

}

Note: Suitable for all frameworks, get_client_ip() Is the ip acquisition function.

get_client_ip function fragment:

function get_client_ip() {
  if(getenv(&#39;HTTP_CLIENT_IP&#39;) && strcasecmp(getenv(&#39;HTTP_CLIENT_IP&#39;), &#39;unknown&#39;)) {
    $ip = getenv(&#39;HTTP_CLIENT_IP&#39;);
  } elseif(getenv(&#39;HTTP_X_FORWARDED_FOR&#39;) && strcasecmp(getenv(&#39;HTTP_X_FORWARDED_FOR&#39;), &#39;unknown&#39;)) {
    $ip = getenv(&#39;HTTP_X_FORWARDED_FOR&#39;);
  } elseif(getenv(&#39;REMOTE_ADDR&#39;) && strcasecmp(getenv(&#39;REMOTE_ADDR&#39;), &#39;unknown&#39;)) {
    $ip = getenv(&#39;REMOTE_ADDR&#39;);
  } else{
    $ip = $_SERVER[&#39;REMOTE_ADDR&#39;];
  }
  return $ip;
}

The above is the entire content of this article, I hope it will be useful to Everyone’s learning helps.


Related recommendations:

php How to quickly remove duplicates from array elements

PHP method of printing binary trees in zigzag order

##php Detailed explanation of how to set up a session that strictly controls the expiration time

The above is the detailed content of Example of creating abnormal login IP detection function using 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