Lock a Webpage with PHP

Based off the Simple Login Script I built a while back, this is an even easier way to protect access to private webpages. This doesn't ask for a username at all, simply a password. If you know the password, you're in, if you don't, no can do. Obviously, this isn't intended for highly secure, user specific data, but anything you want to protect from the general public and share with a select group of people, it's perfect.

To give you an example of a way to use this script, my computer science professor recently discovered that students from other universities were finding work he'd put on his website for previous classes by doing 'answers to homework' type google searches. I suggested using something like this and telling the class the password. Once it's entered, all pages protected by that password are unlocked, so students would feel no hassle, and the rest of the world would not be able to cheat.

<?php session_start(); // If you don't start the session somewhere else function auth($password) { if(!(isset($_SESSION['digigem_auth']) && $_SESSION['digigem_auth'] == $_SERVER['REMOTE_ADDR'] && isset($_SESSION[$password]))) { $error = false; if($_SERVER['REQUEST_METHOD'] == "POST") { if($_POST['pass'] == $password) { $_SESSION['digigem_auth'] = $_SERVER['REMOTE_ADDR']; $_SESSION[$password] = $password; // To ensure any forms behind auth() pages are not accidentally triggered. $_SERVER['REQUEST_METHOD'] == "GET"; return; } else $error = true; } // This is the valid HTML page which will output if user is not authenticated. echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head><title>Please Log In</title></head> <body><div class="auth">'. (($error) ? '<div class="loginError">Login Failed - Try Again</div>' : '') .'<form action="" method="post"> <table> <tr><td>Password:</td><td><input type="password" name="pass"></td></tr> <tr><td>&nbsp;</td><td><input type="submit" value="Submit"></td></tr> </table></form></div></body></html>'; exit; } } ?>


Put auth() in your default function includes file, and call it at the top (above any output) with the parameter being the password you want to set to lock any page from unauthorized access.


<?php include 'auth.inc'; auth('digigem'); // Set the password here // REST OF PAGE GOES HERE ?>

Please leave any feedback about this script in this blog entry.