1

In php, if I have a member system , how do I restraint only certain ip addresses can login as administrator/moderator? I know that there's

$_SERVER["REMOTE_ADDR"] 

but does this included people who used proxy or router as well?

Or there are any others approach?

Thanks

Andrew
  • 2,810
  • 4
  • 18
  • 32

2 Answers2

0

You could try

if ($_SERVER['REMOTE_ADDR'] == 'xxx.xxx.x.xxx') {
    //Allow login as administrator
}

but unfortunately $_SERVER['REMOTE_ADDR'] is sent from the client and can easily be spoofed (See How to get the client IP address in PHP?).

The best bet is to use a combination of the solution above and strong, secure administrator passwords, so should the IP have been spoofed the hacker will still have to guess the strong password!

Community
  • 1
  • 1
JBithell
  • 627
  • 2
  • 11
  • 27
0

You can check for IP range instead to see if the user is connected from the right intranet:

/**
 * Check if a given ip is in a network
 * @param  string $ip    IP to check in IPV4 format eg. 127.0.0.1
 * @param  string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed
 * @return boolean true if the ip is in this range / false if not.
 */
function ip_in_range( $ip, $range ) {
    if ( strpos( $range, '/' ) == false ) {
        $range .= '/32';
    }
    // $range is in IP/CIDR format eg 127.0.0.1/24
    list( $range, $netmask ) = explode( '/', $range, 2 );
    $range_decimal = ip2long( $range );
    $ip_decimal = ip2long( $ip );
    $wildcard_decimal = pow( 2, ( 32 - $netmask ) ) - 1;
    $netmask_decimal = ~ $wildcard_decimal;
    return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) );
}

Source: Gist on GitHub

Akram Fares
  • 1,653
  • 2
  • 17
  • 32