Here is a simple way of password protecting a page in PHP, the username and password are being stored in the file itself but they can easily be fetched from a database with some simple modifications of this code:
<?php
// User name and password for authentication
$username = 'rock';
$password = 'roll';
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ||
($_SERVER['PHP_AUTH_USER'] != $username) or ($_SERVER['PHP_AUTH_PW'] != $password))
{
// The user name/password are incorrect so send the authentication headers
header('HTTP/1.1 401 Unauthorised');
header('WWW-Authenticate: Basic realm="My password protected page"');
exit('<h2>My Password Protected Page</h2>Sorry, you must enter a valid user name and password to access this page.');
}
?>
Related posts:

Web professional in Malta, Europe. Focusing on building visually stunning websites that are easy to maintain, usually using WordPress as the CMS. Web developing since 1995, loving WordPress for more than 5 years.
Leave a Comment
Let us know your thoughts on this post but remember to place nicely folks!