IpFilter.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace common\libs;
  3. use Yii;
  4. use yii\base\Component;
  5. use yii\web\BadRequestHttpException;
  6. use yii\web\Application;
  7. use MaxMind\Db\Reader;
  8. use MaxMind\Db\InvalidDatabaseException;
  9. use MaxMind\Db\AddressNotFoundException;
  10. use common\helpers\LoggerTool;
  11. class IpFilter
  12. {
  13. /**
  14. * @throws BadRequestHttpException
  15. * @return bool
  16. */
  17. public function frontApiCheck($source, $isLogin = false)
  18. {
  19. $request = Yii::$app->request;
  20. $getParams = Yii::$app->request->get();
  21. $postParams = Yii::$app->request->post();
  22. $remoteAddr = $_SERVER['REMOTE_ADDR']; // 获取用户 IP 地址
  23. //如果IP不在指定范围内
  24. if (!self::remoteAddrCall($remoteAddr)) {
  25. $logPreix = $isLogin ? 'nc_ip_filter_login' : 'nc_ip_filter_other';
  26. $getLog = sprintf('%s_%s: remote_ip%s: url(%s): param%s', $source, $logPreix, $remoteAddr, $request->getAbsoluteUrl(), (is_array($getParams) ? json_encode($getParams) : $getParams));
  27. $postLog = sprintf('%s_%s: remote_ip%s: url(%s): param%s', $source, $logPreix, $remoteAddr, $request->getAbsoluteUrl(), (is_array($postParams) ? json_encode($postParams) : $postParams));
  28. //$logPreix . ':remote_ip' . $remoteAddr . ':' . $request->getAbsoluteUrl() . ':' . (is_array($getParams) ? json_encode($getParams) : $getParams);
  29. //$logPreix . ':remote_ip' . $remoteAddr . ':' . $request->getAbsoluteUrl() . ':' . (is_array($postParams) ? json_encode($postParams) : $postParams);
  30. LoggerTool::error($getLog);
  31. LoggerTool::error($postLog);
  32. return false;
  33. }
  34. return true;
  35. }
  36. /**
  37. * 判断IP是否在指定范围内
  38. * @throws AddressNotFoundException
  39. * @throws InvalidDatabaseException
  40. */
  41. public static function remoteAddrCall($remoteAddr): bool
  42. {
  43. // 是否有效的IP
  44. if (!filter_var($remoteAddr, FILTER_VALIDATE_IP)) {
  45. return false;
  46. }
  47. // 替换为 GeoLite2 数据库文件的实际路径
  48. $dbPath = \Yii::getAlias('@common/runtime/geoLite//GeoLite2-Country.mmdb');
  49. // 初始化 MaxMind 数据库读取器
  50. $reader = new \GeoIp2\Database\Reader($dbPath);
  51. // 查询 IP 地址的地理位置
  52. $record = $reader->country($remoteAddr);
  53. // 返回国家名称
  54. $countryName = $record->country->name;
  55. if (!in_array($countryName, ['China', 'Malaysia'])) {
  56. return false;
  57. }
  58. return true;
  59. }
  60. }