Voldemort's Wrath
Voldemort's Wrath

Reputation: 91

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.)

Upvotes: 6

Views: 10314

Answers (5)

john ronald
john ronald

Reputation: 11

I tried

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

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

and I get blocked by the very IP I am accessing it by. How do I fix this?

Upvotes: 1

Mike Robinson
Mike Robinson

Reputation: 8945

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.

Upvotes: 1

Duncan Leung
Duncan Leung

Reputation: 152

If you dont want to bother with the code, put your site on Cloudflare and block ips

Upvotes: 2

Kamrul Khan
Kamrul Khan

Reputation: 3350

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?

Upvotes: 6

mattdaspy
mattdaspy

Reputation: 882

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);
}

Upvotes: 0

Related Questions