kilos
kilos

Reputation: 3

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

Upvotes: 0

Views: 58

Answers (2)

BiOS
BiOS

Reputation: 2304

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.

Upvotes: 1

tsc_chazz
tsc_chazz

Reputation: 206

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

Upvotes: 0

Related Questions