Chris Glasier
Chris Glasier

Reputation: 811

Comparing IP addresses

function getIp() {
  return "<?php echo $_SERVER['REMOTE_ADDR']; ?>";
}

I want to adapt or redo this so that certain actions can only be taken from localhost or my isp server. I can make it work with a little bit of JavaScript for 127.0.0.1 but not for the other.

Appreciate any help; thanks

Upvotes: 3

Views: 7558

Answers (1)

Stefan Arentz
Stefan Arentz

Reputation: 34945

You really want to do this completely on the server. If you check for IPs on the client side then people can very easily hack around that. For example by modifying your code in their browser using a web inspector like Firebug.

Fortunately it is pretty simple to do on the server side:

The $_SERVER['REMOTE_ADDR'] variable is a simple string so you should be able to use string comparison to check for the IPs that you want.

Like for example:

<?php
   if ($_SERVER['REMOTE_ADDR'] == "127.0.0.1" || $_SERVER['REMOTE_ADDR'] == "1.2.3.4") {
       echo "Show secret things here";
   }
?>

Upvotes: 6

Related Questions