0

I'm trying to make my PHP page disallow viewing of the page unless your on a certain IP as viewed below. I'm not sure what to try as I haven't really been doing PHP for very long.

$clientip = $_SERVER['REMOTE_ADDR'];
$whitelistedip = 'realIPhere';

    if ($clientip == $whitelistedip) {
    echo "Welcome $clientip!";
    }
    
    if ($clientip !== $whitelistedip) {
     die("Access Denied");
    }
kilos
  • 3
  • 2

2 Answers2

1

The IP checking bit does not seem to contain mistakes, except that if you only check it with REMOTE_ADDR, the check may fail in some cases, so refer to this question to implement a better method of checking the IP.

Also, unless you have defined them somewhere else, REQUEST_URL and URL_OF_CURRENT_PAGE are no valid variables of the $_SERVER environment. You could be looking into REQUEST_URI, which is indeed a valid one. You can consult them here.

I understand that you would like to only show the HTML page contents if the IP is whitelisted. You may do so using the below shown syntax:

<?php
$clientip = $_SERVER['REMOTE_ADDR'];
$whitelistedip = 'realIPhere';
?>

<?php if ($clientip == $whitelistedip) : ?>

<!-- Place all your HTML here, example: -->
<p>hi</p>

<?php else : ?>

<?php die("Access denied") ?>

<?php endif ?>

In the above case, the <p>hi</p> won't be displayed if the IP is not whitelisted. Instead of the hi, of course, you should put the actual contents of your webpage.

BiOS
  • 2,282
  • 3
  • 10
  • 24
0

I think the test against $URL_OF_CURRENT_PAGE is failing. I don't see why you have that anyway, are you only trying to block in the case that he's getting there directly? If I was coding this it would be somewhat simpler:

if ($clientip == $whitelistedip) {
    echo "Welcome $clientip!";
}
else {
    die ("Access Denied"); 
}
tsc_chazz
  • 206
  • 1
  • 3
  • Yes, That ends the script but I'm trying to make it not make the page appear. Lets say its not the IP so the HTML doesn't appear and instead says something like access denied. https://imgur.com/a/xvKYMW1 – kilos Mar 11 '21 at 20:20