Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibrarySecurity and Blocking

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!

Set a Cookie and Protect an Entire Directory

While coding the website for my brother Harvey's Ruby Riverfront Retreat, I needed a temporary restricted-access directory.

This was to be an easy-to-remember username/password login for Harvey to relay by phone to family and friends — for sneak peeks and feedback. No high security required or desired, just an easy access.

(The cPanel protected directory procedure requires a long and mixed-character password, unsuitable for this purpose.)

This article presents the solution — a cookie setter and .htaccess code combination.

The solution requires two things.

  1. The PHP Cookie Setter Login script to set the cookie and redirect to the protected directory. The login script will need to be in a publicly-accessible directory — not the protected directory.

  2. Four .htaccess lines in the protected directory allow access to the directory only if the browser presents the cookie set by the login script.

The Cookie Setter Login Script

The source code of the PHP Cookie Setter Login script is below.

Customize the script in four places (see the notes following the source code). When customized, save the script as CookieSetterLogin.php (or other *.php file name that you prefer).

Upload the script to a publicly-accessible directory (not the protected directory) and make a note of its URL. (The script must run on the same domain as the protected directory because cookies aren't transferable from one domain to another.)

Here is the source code.

<?php
/*
Login to Set Cookie for Protected-Directory Access
Version 1.0
July 13, 2019
Will Bontrager Software LLC
https://www.willmaster.com/
*/

/* ** *** ** * ** *** ** */
/* Customization section */
/* 4 places to customize */

// Place 1.
// Specify the log-in username:
$un = "fact";

// Place 2.
// Specify the log-in password.
$pw = "fun";

// Place 3.
// Specify the number of days the login cookie shall 
//    survive. Decimal value is acceptable.
$CookieDays = 30.5;

// Place 4.
// URL of the protected directory.
$RedirectPage = "/protected";

/* End of customization section */
/* ** *** ** * **** * ** *** ** */

mb_internal_encoding('UTF-8');
$Emessage = array();
$Process = false;
if( isset($_POST['submitter']) )
{
    if( empty($_POST['un']) ) { $Emessage[] = 'The username needs to be provided.'; }
    if( empty($_POST['pw']) ) { $Emessage[] = 'The password needs to be provided.'; }
    if( ! count($Emessage) ) { $Process = true; }
}
if( $Process )
{
    if( trim(strtolower($un)) != trim(strtolower($_POST['un'])) or $pw != trim($_POST['pw']) )
    {
        $Emessage[] = 'Incorrect login.';
        $Process = false;
    }
}
if( $Process )
{
    setcookie('fact','fun',(time()+intval($CookieDays*24*60*60)),'/');
    header("Location: $RedirectPage");
    exit;
}
?><!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>Login for Protected Directory</title>
<style type="text/css">
* { box-sizing:border-box; }
html, body { font-size:100%; font-family:sans-serif; }
input { font-size:105%; width:100%; }
input[type="text"], input[type="password"] { border:1px solid #999; border-radius:.5em; padding:.35em; }
#content { max-width:300px; margin:.5in auto; }
</style>
</head>
<body><div id="content">
<h1>
Log In
</h1>
<?php if( count($Emessage) ): ?>
<div style="border:3px double red; font-weight:red; color:red; padding:0 1em;">
<p>Note:</p>
<ul><li><?php echo(implode('</li><li>',$Emessage)); ?></li></ul>
</div>
<?php endif; ?>
<form method="post" enctype="multipart/form-data" accept-charset="utf-8" action="<?php echo(htmlspecialchars($_SERVER['PHP_SELF'])); ?>">
<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>
</body>
</html>

Notes:

There are four places to customize in the above script.

  1. Place 1:

    $un = "fact";

    Replace fact with the username the person needs to provide to get the cookie set.

  2. Place 2:

    $pw = "fun";

    Replace fun with the password the person needs to provide to get the cookie set.

  3. Place 3:

    $CookieDays = 30.5;

    Replace 30.5 with the number of days the cookie shall last in the person's browser. A decimal number may be specified.

  4. Place 4:

    $RedirectPage = "/protected";

    Replace /protected with the URL of the protected directory this cookie is for.

    The URL may be relative to document root, as indicated in the example, or it may be the full HTTP or HTTPS URL (with caveat), as in https://example.com/protected

    Caveat:  When redirecting with a full HTTP or HTTPS URL, the redirect protocol and domain name must be the same protocol and domain name that is in the browser's address bar when the cookie is set. (Otherwise the cookie won't be recognized.) http://… and https://… are different protocols. www.example.com and example.com are different domain names when it comes to cookies.

When the CookieSetterLogin.php script has been uploaded to your server, its URL will need to be copied for the .htaccess file of the protected directory.

The Four .htaccess Lines

These four lines need to be put into the .htaccess file of the protected directory. See the notes that follow for information about the customizations.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_COOKIE} !fact=fun
RewriteRule .* /login/CookieSetterLogin.php [L]

Notes:

There are three places to customize. The first two are both on the same line.

  1. Place 1:

    Replace fact with the username used to set a cookie in the Cookie Setter Login script.

  2. Place 2:

    Replace fun with the password used to set a cookie in the Cookie Setter Login script.

  3. Place 3:

    Replace /login/CookieSetterLogin.php with the URL of the Cookie Setter Login script.

    The URL may be relative to document root, as indicated in the example, or it may be the full HTTP or HTTPS URL, as in https://example.com/login/CookieSetterLogin.php

When the Cookie Setter Login script has been installed and the .htaccess file in the protected directory updated, then the system is ready to use.

Test the system by using the script to set a cookie. After the cookie is set, the script should redirect you to the protected directory — which should let you in without protest. If the cookie is not present, the .htaccess lines redirect the browser to the login script.

(This article first appeared with an issue of the 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