LoginIpChecker.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: sunmoon
  5. * Date: 2018/8/25
  6. * Time: 上午10:49
  7. */
  8. namespace common\libs;
  9. class LoginIpChecker {
  10. private $_ip;
  11. private $_bindIp;
  12. /**
  13. * LoginIpChecker constructor.
  14. * @param $ip
  15. * @param $this->_bindIp
  16. */
  17. public function __construct($ip, $bindIp) {
  18. $this->_ip = $ip;
  19. $this->_bindIp = $bindIp;
  20. }
  21. /**
  22. * 掩码模式验证
  23. * @return bool
  24. */
  25. private function _mask(){
  26. $ip = (double) (sprintf("%u", ip2long($this->_ip)));
  27. $s = explode('/', $this->_bindIp);
  28. $start = (double) (sprintf("%u", ip2long($s[0])));
  29. $len = pow(2, 32 - $s[1]);
  30. $end = $start + $len - 1;
  31. if ($ip >= $start && $ip <= $end) {
  32. return true;
  33. }
  34. return false;
  35. }
  36. /**
  37. * 验证ip段
  38. * @return bool
  39. */
  40. private function _range(){
  41. if(strpos($this->_bindIp, '-') !== false){
  42. list($startIp, $endIp) = explode('-', $this->_bindIp);
  43. if(strpos($endIp, '.') === false){ //127.0.0.2-254
  44. $start = explode('.', $startIp);
  45. $endIp = $start[0] . '.' . $start[1] . '.' . $start[2] . '.' . $endIp;
  46. }
  47. $startIp = $this->_getIplong($startIp);
  48. $endIp = $this->_getIplong($endIp);
  49. $ip = $this->_getIplong($this->_ip);
  50. if($ip >= $startIp && $ip <=$endIp){
  51. return true;
  52. }
  53. return false;
  54. }else{ //单个ip 127.0.0.1
  55. if($this->_bindIp == $this->_ip){
  56. return true;
  57. }
  58. return false;
  59. }
  60. }
  61. /**
  62. * bindec(decbin(ip2long('这里填ip地址')));
  63. * ip2long();的意思是将IP地址转换成整型 ,
  64. * 之所以要decbin和bindec一下是为了防止IP数值过大int型存储不了出现负数。
  65. * @param $ip
  66. * @return float|int
  67. */
  68. private function _getIplong($ip){
  69. return bindec(decbin(ip2long($ip)));
  70. }
  71. /**
  72. * 验证
  73. * @return bool
  74. */
  75. public function validate(){
  76. if(strpos($this->_bindIp, '/') !== false){ //掩码模式 127.0.0.1/24
  77. $result = $this->_mask();
  78. }else{ // ip段10.0.0.1-254 OR 10.0.0.1-10.0.0.254
  79. $result = $this->_range();
  80. }
  81. return $result;
  82. }
  83. }