2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでアクセス元のIPが一定レンジ内のIPに合致するかチェックするメソッド

Posted at

アクセス元のIPをチェックし、合致する場合はtrueを返してくれるだけの単純なメソッドを書いた。

usage
$ipAddress = array('10.1.192.0/24', '10.1.4.0/23', '172.20.244.0/24');//例1 どれかに合致してるのかチェック
$ipAddress = '10.1.192.0/24';//例2 一つの場合はstringでもいいのよ

if (permissionIp::judgeIpAddress($ipAddress)) {
    //合致
}
permissionIp.php
class permissionIp
{
    /**
     * アクセス者が引数で与えられたIPアドレスに合致しているかを調査
     * @param array or string $ipAddress
     * @return boolean
    */
    static public function judgeIpAddress($ipAddress)
    {
        if (! is_array($ipAddress)) {
            $ipAddress = array($ipAddress);
        }

        $sepRemoteIp = explode('.', $_SERVER['REMOTE_ADDR']);

        foreach ($ipAddress as $judgeIp) {
            $tmp = explode('/', $judgeIp);
            $sepIp = explode('.', $tmp[0]);
            if (isset($tmp[1])) {
                $subnet = (int)$tmp[1];
            } else {
                $subnet = 32;
            }
            if (count($sepIp) != 4 || count($sepRemoteIp) != 4) {
                return false;
            }

            if ($subnet >= 24 && $subnet <= 32) {
                $add = pow(2, (32 - $subnet));

                if ($sepRemoteIp[0] == $sepIp[0] &&
                $sepRemoteIp[1] == $sepIp[1] &&
                $sepRemoteIp[2] == $sepIp[2] &&
                $sepRemoteIp[3] >= $sepIp[3] && $sepRemoteIp[3] < ($sepIp[3] + $add)) {
                    return true;
                }
            } elseif ($subnet >= 16 && $subnet <= 23) {
                $add = pow(2, (24 - $subnet));

                if ($sepRemoteIp[0] == $sepIp[0] &&
                $sepRemoteIp[1] == $sepIp[1] &&
                $sepRemoteIp[2] >= $sepIp[2] && $sepRemoteIp[2] < ($sepIp[2] + $add) &&
                $sepRemoteIp[3] >= 0 && $sepRemoteIp[3] < 256) {
                    return true;
                }
            } elseif ($subnet >= 8 && $subnet <= 15) {
                $add = pow(2, (16 - $subnet));

                if ($sepRemoteIp[0] == $sepIp[0] &&
                $sepRemoteIp[1] >= $sepIp[1] && $sepRemoteIp[1] < ($sepIp[1] + $add) &&
                $sepRemoteIp[2] >= 0 && $sepRemoteIp[2] < 256 &&
                $sepRemoteIp[3] >= 0 && $sepRemoteIp[3] < 256) {
                    return true;
                }
            }
        }
        return false;
    }
}
2
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?