简体   繁体   中英

Only allow users on page if IP address is approved

How can I make an HTML (and CSS/PHP/JavaScript) document which only allows certain IP addresses on a page?

(I am not asking how to find IP address with PHP, but how to allow access to a page based on an IP address.)

put this on the top of your php file and update the allowedIps variable with the IPs that you want to allow.

$allowedIps = ['198.x.x.x', '200.x.x.x'];
$userIp = $_SERVER['REMOTE_ADDR'];

if (!in_array($userIp, $allowedIps)) {
    exit('Unauthorized');
}

for non PHP files (eg .html, .css) you will have to update your .htaccess file to add file specific permission. The following SOF thread should help: (assuming you are using apache server)

.htaccess: how to restrict access to a single file by IP?

如果您不想打扰代码,请将您的网站放在Cloudflare上并阻止ips

Try this with PHP :

function CheckIPAccess() {
  //allowed IP. Change it to the IP addresses you want to allow to access your webpage

  $allowedip = '127.0.0.1';
  $ip = $_SERVER['REMOTE_ADDR'];
  return ($ip == $allowedip);
}

Usually, IP restrictions are done at the web-server configuration level, so that unauthorized IPs simply can't reach your code at all.

It would actually be quite messy to try to do this kind of check within your application – "you'd undoubtedly miss one" – but the server can easily do it for you.

(I do not recommend attempting to use IPs for privilege checking and so forth ... "IPs change. Frequently. Very messy. Very ...")

Even stronger yet would be firewalls, and maybe VPNs. You really want to keep intruders as far away as possible and to give them as little information as possible. (For instance, why should they even be able to detect that the web-server exists?) Strive to make the entire setup as "hardened" as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM