Webmaster tips » PHP

Nov 21, 2006
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 can use some open-source php script (for example, statistics frontend), and you can not be fully assured 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 this script "entry point" from others.
  • You can have some important private data you don't want to be accessible by aliens.

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 function CheckAccess(), so you can choose the better variant to use in your scripts. The basic technique is to place CheckAccess() in the beginning of your "private" scripts. Please note, our examples are very simple and can not be treated as comprehensive paranoid secure solution, nevertheless they can do their job.

Restrict access by IP address

If you have static IP address, you can hardcode it in your verification function something 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 try the first method placing something like this 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';

?>

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

In my opinion, the better way is to make unwanted visitor/spider/hacker think the page does not exist. It can be done by returning "404 Not Found" HTTP header as 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 solutions you can use some 3rd-party solutions and libraries like Pear::Auth or read more advanced tutorials like Tutorial “PHP-Based User Authentication” from Zend.

Print! Print this article   Bookmark:

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. 24 people have rated this article.
Use your mouse pointer to select as many stars as you want, and press the left mouse button to vote.
  • 3.9 out of 5 Stars
  • 1
  • 2
  • 3
  • 4
  • 5
Other PHP Articles
Rating: 5 stars
5 Tools for Spying on Your Competition by Kim Roach (Nov 16, 2006)
Did you know that an ancient Chinese military document unlocks many of the secrets to your online success? This book is called "The Art of War" and was written during the 6th century by Sun Tzu. This famous document is one of the oldest and most famous studies of strategy and has had a huge influence on military planning as well as business tactics...
Rating: 4.5 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.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: 4 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.5 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...