Easy Authentication in PHP


I've been telling myself for a while that I should build my own login script, and now I've finally done it. This script will succinctly and easily allow you to lock any page from prying eyes (similar to .htaccess and .htpasswd, but without the hassle). This script is not meant to work as a user management system, as it only allows for one username and one password. Instead, use this to password protect any administrative or otherwise private pages that you only want a few people to have access to.

<?php session_start(); // If you don't start the session somewhere else // This function tests to see if user is already authenticated //and if not outputs a form, the page footer, and exit function authenticate($username, $password) { if(!authentic()) { $error = false; if($_SERVER['REQUEST_METHOD'] == "POST") { if($_POST['user'] == $username && $_POST['pass'] == $password) { $_SESSION['digigem_auth'] = md5($_SERVER['REMOTE_ADDR']); $_SERVER['REQUEST_METHOD'] = "GET"; return; } else $error = true; } ////////////////////////////// // Insert your own page-header code here for a properly formatted page // global $_template; // $_template->header("Please Log In"); ////////////////////////////// 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">'; ////////////////////////////// echo ' <div class="auth">'. (($error) ? ' <div class="smallNotice">Login Failed - Try Again</div>' : '') .' <form action="" method="post"> <table> <tr> <td>Username:</td> <td><input type="text" name="user" /></td> </tr> <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>'; ////////////////////////////// // Insert your own page-footer code here for a properly formatted page // $_template->footer(); ////////////////////////////// echo '</div></body></html>'; ////////////////////////////// exit; } } // This function returns true if user is authentic function authentic() { return (isset($_SESSION['digigem_auth']) && $_SESSION['digigem_auth'] == md5($_SERVER['REMOTE_ADDR'])); } ?>

Instructions

Put authenticate() and authentic() in your default function includes file, and call authentic() at the top (above any output) to lock any page from unauthorized access. You can set the username and password as default parameters of authentic() and just call authenticate() when needed, without specifying the username and password every time. Use authentic() to output content only authentic users should see on public pages.

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