Webmaster tips » PHP


wmtips.com

3 Simple Ways to restrict access to your webpages using PHP

Average rating
  • 3.9 out of 5 Stars
Rate this article

Why do you need to restrict access to some of your scripts or webpages? 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 what 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.

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 how you can implement such "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 our examples are very simple and can not be treated as a comprehensive paranoid secure solution, nevertheless they do their job.

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

?>  

Specify 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:


<?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:password in HTTP headers as plain text. If you need stronger security, consider using Secure Sockets Layer (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
  echo 'Access denied!';
  exit;
}

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

?>

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

Even a better way is 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';

?>

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.

SEO PowerSuite - all-in-one SEO tool
About The Author
Webmaster tips and tools. Webmaster tips: HTML, CSS, SEO, AdSense. SEO Tools: Site information tool, Search Engine Update Monitor, Google PR checker, Keyword Density analyzer, AdSense Ads preview and more.
Rate This Article
How would you rate the quality of this content?
Currently rated: 3.9 out of 5 stars. 28 people have rated this article.
  • 3.9 out of 5 Stars
  • 1
  • 2
  • 3
  • 4
  • 5
Related Articles
  • Rating: 3.6 stars
    Are you using the power of PPC to get the international traffic you deserve? This sort of advertising can put a brand or service in front of global customers who would otherwise be out of reach.Even if you already benefit from PPC (pay-per-click) advertising, using the English language will only take you so far in the rapidly changing online landscape...
  • Rating: 3.8 stars
    Auto Optimize Your MySQL Tables Script by John Miller (May 25, 2008)
    In my quest to make our clients MySQL driven ecommerce websites running fast, I've pieced together a script and cron job that will save you some support calls down the road....
  • Rating: 4.7 stars
    43 Tips for Optimizing PHP code by Reinhold Weber (Oct 18, 2007)
    Here is the list of 43 short tips you can use for writing an optimized and more efficient PHP code.. ..
  • Rating: 3.6 stars
    Content Compression Using PHP by Paul Katsande (Mar 3, 2007)
    HTTP 1.0 introduced the idea of content encodings. A browser/client can notify the server that it can accept compressed content by sending the Accept-Encoding header. The Accept-Encoding header can be set as follows Accept-Encoding: gzip,deflate or with just one of gzip or deflate...
  • Rating: 4.1 stars
    Regular expressions made easy by wmtips.com (Nov 19, 2006)
    Regular expressions is a very powerful instrument to manipulate and extract strings. However not all PHP developers know how to use regular expressions, so this simple tutorial is intended to everyone who wants to learn them...
Top Wordpress Themes