Skip to content
Advertisement

Disallowing user to view page

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement