-2

I need to deny access to all users except 127.0.0.1 to one of my PHP files. I've tried using the following snippet in my .htaccess file:

<Files /file.php>
    Order deny,allow
    Allow from 127.0.0.1
    Deny from all
</Files>

…but that isn't working, so I'm looking for a solution without .htaccess. Preferably I want a snippet that I can insert at the top of the page to determine whether the user is localhost or not. If they are not, it will send a 403 error and stop the page from continuing. How could I write such a thing?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
user3462992
  • 175
  • 2
  • 9

4 Answers4

1

Try this.

Place this on top of the PHP file which you want to protect.

if($_SERVER['REMOTE_ADDR'] !== '127.0.0.1'){
     header('HTTP/1.0 403 Forbidden');
     echo 'You are not authorized to view this page';
     exit();
}

You can also do this by using .htaccess.

<Files "file.php">
    ErrorDocument 403 /html_file_that_displays_403_message.html
    Order deny,allow
    Deny from all
    Allow from 127.0.0.1
</Files>
Jay Bhatt
  • 5,601
  • 5
  • 40
  • 62
0

You can use $_SERVER['REMOTE_ADDR'] like this:

<?php
if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1')
{
    http_response_code(403);
    echo 'Access denied';
    exit;
}

According to this answer, it's safe to trust this variable. Some sites suggest also checking HTTP_X_FORWARDED_FOR. This might, however, be uncalled for in your case - this header is used by proxies to determine original IP and can be easily counterfeited. REMOTE_ADDR is, on the other hand, added by Apache (nginx) and its value holds the exact IP address that connection was made from.

You should, probably, rethink your approach. Instead of firewalling access to that file, you might want to add some kind of authorization, using, for example, HTTP Digest. This allows you to limit the access to people rather than hosts.

Community
  • 1
  • 1
rr-
  • 14,303
  • 6
  • 45
  • 67
0

Try this at the top of your file :

if (!$_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']){
   header('No Remote Access Allowed', true, 400);
   exit;
}
Tanatos
  • 1,857
  • 1
  • 13
  • 12
0
<?php
if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1'){
header('HTTP/1.0 403 Forbidden');?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>403 Forbidden</title>
</head>
<body>
    <h1>Forbidden</h1>
    <p>You don't have permission to access this page on this server.</p>
</body>
</html>
<?php }?>