PHP HTTP Autentication

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:

  1. Use WordPress Functions Outside of WordPress
  2. Comparing PHP Isset, Empty, iS_null
  3. Mount Network Folders on Ubuntu
  4. Roboform : The Solution to All Your Login Problems
  5. Password Protecting Your WordPress Website or Blog

Leave a Comment

Let us know your thoughts on this post but remember to place nicely folks!