Configuring IP Access Restrictions for Modules in ThinkPHP
This guide explains how to configure module IP access restrictions in ThinkPHP by adding 'allow_module_ip' and 'deny_module_list' entries to config.php, shows the recommended placement, and demonstrates the necessary modifications to the framework's App.php file to enforce the rules.
This article provides step-by-step instructions for setting up IP-based access control for modules in a ThinkPHP application.
In config.php you can add an 'allow_module_ip' array to specify which IPs are permitted to access particular modules, e.g., allowing all IPs for the admin module or restricting it to specific addresses. You can also define a 'deny_module_list' to block modules entirely.
The configuration should be placed near the other module settings, typically after the 'default_controller' entry.
To make the framework respect these settings, modify thinkphp/library/think/App.php . Within the module method, after determining the requested module, the code checks if $config['allow_module_ip'][$module] exists and, if so, verifies the client IP against the allowed list, disabling the module when the IP is not permitted.
The relevant code snippet looks like:
<code>'allow_module_ip' => ['admin' => '*'], // all IPs can access admin module
// or
'allow_module_ip' => ['admin' => ['127.0.0.1','192.168.1.100']], // only these IPs can access admin
'deny_module_list' => ['common'], // modules to deny
// In App.php
public static function module($result, $config, $convert = null) {
// ... existing logic ...
if (isset($config['allow_module_ip'][$module])) {
$allowIps = $config['allow_module_ip'][$module];
if (!in_array($_SERVER['REMOTE_ADDR'], $allowIps) && $allowIps != '*') {
$available = false;
}
}
// ... rest of method ...
}
</code>After applying these changes, the application will enforce the defined IP restrictions for each module.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.