Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryCookies and Browser Interaction

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Cookie Directory Protection

Access to any subdirectory can be restricted with a cookie. Browsers and bots that don't have the cookie don't get in.

Any number of subdirectories on a domain can be restricted with the same cookie.

With the cookie, your browser can access the subdirectory(ies) from any device, with any reliable internet connection. You can use any browser, so long as it has the cookie.

The protection is done with the .htaccess file. Here is an example.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !cookie_name=cookie_value
RewriteRule .* https://example.com/setcookie.php [R=302,L]

In the above source code, make the following changes:

cookie_name needs to be changed to the cookie name required to access the subdirectory.

cookie_value needs to be changed to the cookie's value required to access the subdirectory.

https://example.com/setcookie.php needs to be changed to the location of the cookie-setting script (see further below).

To implement cookie directory protection, do two things.

  1. Install the script below to set the cookie.

  2. Paste the .htaccess file into the directories you want to protect.

The script source code is below. It is a PHP script. Customizations follow — the cookie name, cookie value, how long the cookie lasts, and a username and password that is required to set the cookie.

<?php
/*
Log In for Cookie Directory Protection
Version 1.0
January 12, 2024
Will Bontrager Software LLC
https://www.willmaster.com/
*/

// // // // // //
// Customizations

// Login username.
// May contain spaces. No length limit. Not case-sensitive.
$Username = 'JustMe';

// Login password.
// Password is case-sensitive and may be either an exactly 40-character sha1 encryption 
//   or plain text of less or more than 40 characters (not exactly 40).
// sha1 encryption may be done at https://www.willmaster.com/secure/encrypt.php or with 
//   PHP code: $encrypted=sha1("PASSWORD"); echo $encrypted;
$Password = '8efd86fb78a56a5145ed7739dcb00c78581c5375';

// Cookie name.
// Starts with a letter. May contain letters, numbers, and underscore characters.
$CookieName = 'a_cookie_name';

// Cookie value.
// Any keyboard characters.
$CookieValue = 'the_cookie_value';

// Lifetime of cookie.
// Use either digit 0 (for volatile cookie) or specify number of hours. The hours number may contain a decimal.
$CookieDays = 30.5;

// End of customizations section.
// // // // // // // // // // //

mb_internal_encoding('UTF-8');
$Error = false;
if( isset($_POST['submitter']) )
{
   if( (strtolower(trim($Username)) == strtolower(trim($_POST['un'])) ) and PasswordOK($Password,$_POST['pw']) )
   {
      $CookieDays = intval($CookieDays);
      $CookieName = preg_replace('/^[^a-zA-Z]+/','',$CookieName);
      $CookieName = preg_replace('/[^a-zA-Z_0-9]+/','',$CookieName);
      setcookie($CookieName,$CookieValue,($CookieDays>0?(time()+intval($CookieDays*24*60*60)):0),'/','',true,false);
      $_COOKIE[$CookieName] = $CookieValue;
   }
   else { $Error = 'Login incorrect.'; }
}
function PasswordOK($p,$pw)
{
   $p=trim($p);
   $pw=trim($pw);
   if(strlen($p)==40) { $pw = sha1($pw); }
   return($p==$pw);
}
$CookieIsSet = ( isset($_COOKIE[$CookieName]) and $_COOKIE[$CookieName]==$CookieValue ) ? true : false;
?><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Directory Access Cookie</title>
<style type="text/css">
* { box-sizing:border-box; }
html, body { font-size:100%; font-family:sans-serif; }
input { width:100%; font-family:sans-serif; font-size:1rem; }
input[type="password"], input[type="text"] { border:1px solid #ccc; padding:4px; border-radius:3px; }
</style>
</head>
<body><div id="content";
<h1 style="text-align:center;">
Set Directory Access&nbsp;Cookie
</h1>
<?php if( $CookieIsSet ): ?>
<p style="text-align:center;">
The cookie is set. You have access to the directory.
</p>
<?php else: ?>
</p>
<form enctype="multipart/form-data" action="<?php echo($_SERVER['PHP_SELF']) ?>" method="post" accept-charset="utf-8">
<div id="get-login" style="max-width:300px; margin:0 auto;">
<?php if($Error): ?>
<p style="border:3px double red; padding:1em;">
<?php echo($Error); ?>
</p>
<?php endif; ?>
<p>Username<br><input type="text" name="un"></p>
<p>Password<br><input type="password" name="pw"></p>
<p><input type="submit" name="submitter" value="Log In"></p>
</form>
</div>
<?php endif; ?>
</body>
</html>

The above PHP script has a customizations area. These notes let you know what is expected.

  1. In the "Login username" part, replace JustMe with the login username.

    The username is not case-sensitive. It may be any length. And it may contain spaces.

  2. In the "Login password" part, replace 8efd86fb78a56a5145ed7739dcb00c78581c5375 with your password. Spaces are acceptable. The characters will be case-sensitive. Replace your password using one of the following methods:

    • Any series of keyboard characters either less than 40 characters in length or more than 40 characters in length.

    • The password may be sha1 encrypted (which results in exactly 40 characters in length). The 40-character sha1 encryption form can be used. Or, use this PHP code to encrypt your password:

      <?php $encrypted=sha1("PASSWORD"); echo $encrypted; ?>
      
  3. In the part for "Cookie name", replace a_cookie_name with the name of the cookie. The cookie name needs to begin with a letter. The rest of the cookie name may be composed of letters, numbers, and underscore characters.

  4. In the part for "Cookie value", replace the_cookie_value with the value for the cookie. Any keyboard characters may be used here.

  5. In the "Lifetime of cookie" part, replace 30.5 with the number of hours you want the cookie to last. The number may contain a decimal. If you want the cookie to go poof when the browser is exited, specify the number 0 as the number of hours.

Save the above cookie-setting PHP script as setcookie.php or other *.php file name. Upload setcookie.php into the document root directory (where your website's home or index page is at). Make a note of its URL.

Caveat: Don't upload the above PHP script into a subdirectory that will be protected by the cookie with the .htaccess file. You wouldn't be able to get your browser to the cookie-setting script.

When you upload the .htaccess file into a subdirectory (see beginning of this article), replace the cookie name and cookie value with the same cookie name and cookie value you specified in the PHP cookie-setting script. And replace the redirect URL with the URL where you uploaded the cookie-setting script.

Verify the system works.

There are other ways to protect a subdirectory from unauthorized access. See Various Ways to Protect a Directory for a few.

Protecting subdirectories by cookie can be an especially good method when access needs to be allowed from various internet connections.

(This content first appeared in Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC