3 Simple Ways To Restrict Access To Your Webpages Using PHP

By / Updated: Mar 20, 2020 /
  • 4.2 out of 5 Stars
Published in: PHP

Why should you need to restrict access to some of your scripts or web pages? There are can be several reasons to do this:

  • You are using some kind of open-source php script (for example, statistics frontend), and aren't sure that your data completely safe. Many open-source scripts have vulnerabilities, allowing hackers to gain access to your data, so you may want to hide the "entry point" of this script from others.
  • You can have some important private data you don't want to be accessible by unauthorized visitors.
Forbidden

So, you need to "hide" your pages from search engine spiders, random visitors and other unwanted persons. In this article we'll examine several techniques and illustrate how you can implement such an "access restriction" with PHP.

All our examples will implement the CheckAccess() function, so you can choose the better matching variant to use in your scripts. The basic technique is to place CheckAccess() in the beginning of your "private" scripts.

Please note that despite the fact that our examples are fully functional, they are still very simple ones and can not be treated as a comprehensive paranoid secure solution.

Restrict Access by IP Address

If you have a static IP address, you can hardcode it in your verification function somehow like this:

<?php

//This function returns True if visitor IP is allowed.
//Otherwise it returns False
function CheckAccess()
{
  //allowed IP. Change it to your static IP
  $allowedip = '127.0.0.1';

  $ip = $_SERVER['REMOTE_ADDR'];
  return ($ip == $allowedip);
}

?>

If you want to allow access to your PHP page only for the range of static IP addresses (for example, IP range of your organisation, school, etc.), your verification function could be as follows:

<?php

//This function returns True if visitor IP within allowed range.
//Otherwise it returns False
function CheckAccess()
{
  //allowed IP range start, change it to yours
  //please note that $toip must be greater than $fromip 
  $fromip = '127.0.0.1';
  //allowed IP range end
  $toip = '127.0.0.100';

  $ip = ip2long($_SERVER['REMOTE_ADDR']);
  return ($ip >= ip2long($fromip) && $ip <= ip2long($toip));
}

?> 

Add an Additional Hidden Parameter

This very simple technique can be used if you want to restrict access to the PHP script and do not want to write much code. You can get access to your script by supplying arbitrary additonal parameter within the script URL, e.g.: http://www.yoursite.com/mystats.php?secretkey=secretvalue. Without this parameter you can return 404 HTTP (Page Not Found) response code as described below.

 <?php 
  
  //This function returns True if query string contains 
  secretkey and secretvalue. 
  //Otherwise it returns False 
  function CheckAccess()   
  { 
    return @$_GET['secretkey']=='secretvalue';   
  } 
  
  ?>  

Restrict Access Using Basic HTTP Authentication

The Basic HTTP authentication forces visitor's browser to show prompt asking for username and password in order to access restricted area. Our CheckAccess() function could be implemented like this:

Build Your Website with Namecheap - Get Privacy Protection Free Forever
<?php

//This function returns True if login:testuser and password:testpass are provided
//Otherwise it returns False
function CheckAccess()
{
  $result = (isset($_SERVER['PHP_AUTH_USER']) &&
            $_SERVER['PHP_AUTH_USER'] == 'testuser' &&
            $_SERVER['PHP_AUTH_PW'] == 'testpass');

  if (!$result)
  {
   header('WWW-Authenticate: Basic realm="Test restricted area"');
   header('HTTP/1.0 401 Unauthorized');
   return false;
  }
  else
   return true;
}
?>

Note that with this authentication method your browser will pass your username and password in HTTP headers as plain text. If you need stronger security, consider using HTTPS protocol.

Make the Page "Invisible" to the User or Search Engine Spider

Ok, now you have written simple checking function CheckAccess. How can you use it? Firstly you can save the function implementation in the php file for further inclusion in your scripts. After that you can invoke CheckAccess somewhere in the beginning of your script:

<?php
//include file with CheckAccess implementation
include 'myauth.php';

if (!CheckAccess())
{
  //show the access denied message and exit script
  die('Access denied!');
}

//access granted, normal flow
echo 'OK';
?>

After checking the credentials, if the check is not passed, your script will output "Access denied" message.

But, there is even a better way to make an unwanted visitor/spider/hacker think that the page does not exist. It can be done by returning "404 Not Found" HTTP header as a response and can be implemented like this:

<?php

//include file with CheckAccess implementation
include 'myauth.php';

if (!CheckAccess())
{
  header('HTTP/1.0 404 Not Found');
  exit;
}

//access granted, normal flow
echo 'OK';
?>

In the case you don't want to "hide" the page, instead of HTTP 404, you can return a HTTP 403 "forbidden" header for the browsers and search engines with the following code:

header("HTTP/1.1 403 Forbidden");

Conclusion

In this article we have examined simple web access restriction approaches in PHP: by IP address, with secret parameter, using Basic HTTP authentication. For more complicated tasks, you can use some 3rd-party libraries like PHP-Auth.

SEMrush

Rate This Article

How would you rate the quality of this content?
Currently rated: 4.2 out of 5 stars. 22 users have rated this article. Select your rating:
  • 4.2 out of 5 Stars
  • 1
  • 2
  • 3
  • 4
  • 5

About The Author

Webmaster tips and tools. Webmaster tips: HTML, CSS, SEO, AdSense. SEO Tools: Site information tool, Pagerank checker, Keyword Density Analyzer and more.
Online Press Release Service.