IP Address Filtering for User Logins
In this article, we will implement a feature that allows users to restrict their login access based on their IP addresses. This feature will be added to user preferences, enabling users to specify which IP addresses are permitted to log in.
How It Works
When a user attempts to log in, the system will check their IP address against a list of allowed IPs. The user can specify up to five IP restrictions, which can be in the following formats:
- Full IP:
67.31.85.47 - Subnet:
67.31.85.* - Wildcard:
67.31.*.* - Partial Wildcard:
67.*.*.*
If the user's IP matches any of the specified formats, the login will be successful. If not, access will be denied.
Example IP Restrictions
Here’s an example of how users might configure their allowed IPs:
67.31.*.*
167.77.47.*
62.11.28.28
25.57.*.*
169.*.*.*
Implementation Strategy
To implement this feature efficiently, we can use the following approach:
- Extract the User's IP Address: Use PHP's
$_SERVER['REMOTE_ADDR']to get the user's IP. - Split the IP Address: Use the
explodefunction to break the IP into its components. - Check Against Allowed IPs: Loop through the user's allowed IPs and compare each one against the user's IP.
Performance Consideration
While the initial thought might be to check each segment of the IP against the allowed IPs, this can be slow if done naively. Instead, consider converting the IP addresses to integers and using bitwise operations for comparison. This can significantly speed up the process.
Example Code Snippet
Here’s a simple PHP example to illustrate the concept:
$userIP = $_SERVER['REMOTE_ADDR'];
$allowedIPs = [
'67.31.*.*',
'167.77.47.*',
'62.11.28.28',
'25.57.*.*',
'169.*.*.*'
];
function ipMatches($userIP, $allowedIP) {
$userParts = explode('.', $userIP);
$allowedParts = explode('.', $allowedIP);
for ($i = 0; $i < 4; $i++) {
if ($allowedParts[$i] !== '*' && $allowedParts[$i] !== $userParts[$i]) {
return false;
}
}
return true;
}
foreach ($allowedIPs as $allowedIP) {
if (ipMatches($userIP, $allowedIP)) {
// Successful login
break;
}
}
Conclusion
Implementing IP address filtering can enhance security by ensuring that only authorized users can log in from specified IP addresses. By using efficient comparison methods, we can maintain performance while providing this important feature.