Snowboarding and more

How to Password-Protect a Website

Last year when I designed and developed our family book, I needed an easy way to password-protect the entire site. My aunt, who is the author, doesn’t want the book to be public. She just wants to share it with family members. I can’t remember the resource I used; therefore, I would like to document it here just in case others find it useful.

Place the follow code at the top of the page you want to be password-protected:

<?php
 	/* Your password */
	 $password = 'yourpassword';

	 if (empty($_COOKIE['password']) || $_COOKIE['password'] !== $password) {
	 // Password not set or incorrect. Send to login.php.
	 header('Location: /login.php');
	 exit;
         }
?>

Create a login page (login.php). It should live on the top directory. Here’s the PHP code:

<?php
	/* Your password */
	$password = 'yourpassword';

	/* Redirects here after login */
	$redirect_after_login = 'index.php';

	/* Will not ask password again for */
	$remember_password = strtotime('+7 days'); // 7 days

	if (isset($_POST['password']) && $_POST['password'] == $password) {
	setcookie("password", $password, $remember_password);
	header('Location: ' . $redirect_after_login);
	exit;
	}
?>

Create HTML log-in form in login.php:

<form method="POST">
	<input type="text" name="password" placeholder="Enter password">
	<input type="submit" name="Submit" value="Submit" class="button">
</form>

The webpage is set to expired in 7 days. If you want a logout link, create a logout.php page with the following codes:

<?php
	/* Your password */
	$password = 'yourpassword';

	if (empty($_COOKIE['password']) || $_COOKIE['password'] !== $password) {
	// Password not set or incorrect. Send to login.php.
	header('Location: /login.php');
	exit;
        }
?>
Snowboarding and more