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, a statistics dashboard), and aren't sure that your data is 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 Forbidden](jpg/forbidden.jpg)
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() at the beginning of your "private" scripts.
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, the IP range of your organization, school, etc.), your verification function could be as follows:
<?php
//This function returns True if the visitor IP is within the 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 an additional secret parameter within the script URL, e.g.: http://www.yoursite.com/mystats.php?secretkey=secretvalue. Without this parameter, you can return the HTTP 404 (Page Not Found) response code as described below.
<?php
//This function returns True if the 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 the visitor's browser to show a prompt asking for a username and password in order to access a 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 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 the 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 at 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 the "Access denied" message.
But, there is an even better way to make an unwanted visitor/spider/hacker think that the page does not exist. It can be done by returning the "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 when you don't want to "hide" the page but want to indicate that this page requires authentification, instead of HTTP 404, you can return the HTTP 403 "Forbidden" header using 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, and using the Basic HTTP authentication.
For more complicated tasks, you can use a 3rd-party library like PHP-Auth or PHPAuth. Also, there are more than 1000 repositories on GitHub to choose from.