tutorialtastic

Creating a Secure PHP Login Page

If you run a popular graphics site or have content that you only want exclusive visitors to see, it is often quite popular to set silly rules with hidden links that visitors have to find before they can find the downloadables. Why bother, when you could simply put your goodies on a password protected page and then give the password out to anyone you want? This tutorial will show you how.

First, we need to create our file. It really doesn't matter what you call it — login.php, mygoodies.php, ieatchocolatebiscuits.php — as long as it has the .php extension. Create your page, call it what you like, open it up and insert the follow:

<?php
$username = "user";
$password = "pass";
$randomword = "bibblebobblechocolatemousse";
?>

The code is relatively easy to understand. We're opening the PHP declaration and assigning a value to our username, password and randomword variables. Each one of these needs to be customised by you. Make sure you have a decent password and a non-obvious username: i.e. not admin, that's the first thing people guess when trying to break into password-protected pages. Lastly is the third variable which can be absolutely anything you like, but I would advise making it long and completely random. You don't have to remember it, it's for extra security only.

Next, we can check to see if a cookie exists thus proving whether or not a visitor has visited before and if they've been logged in. This might seem a little sudden because we've not even set the cookie yet, but it means that repeat visitors will have the actual content processed and displayed quicker. So, let's check if the cookie exists and if it is valid:

<?php
$username = "user";
$password = "pass";
$randomword = "bibblebobblechocolatemousse";

if (isset($_COOKIE['MyLoginPage'])) {
   if ($_COOKIE['MyLoginPage'] == md5($password.$randomword)) {
?>

Don't try and run the page yet, it'll give you errors! Anyway, what we've done there is use the isset() function to check for existance, and then compared the cookie to a hashed version of the password and random security word — this is because this data will be hashed further down the script before it's stored in the cookie. Now, we can add our content. It'll be easiest if we leave PHP 'closed' so that we don't have to worry about escaping quotation marks. We'll also need to add an else { } to make sure that people with fake cookies can't get to our stuff:

<?php
$username = "user";
$password = "pass";
$randomword = "bibblebobblechocolatemousse";

if (isset($_COOKIE['MyLoginPage'])) {
   if ($_COOKIE['MyLoginPage'] == md5($password.$randomword)) {
?>

      CONTENT HERE
<?php
      exit;
   } else {
      echo "<p>Bad cookie. Clear please clear them out and try to login again.</p>";
      exit;
   }
?>

Now that we've dealt with with the cookie stuff we can actually add the login form which in the end will set the cookie we're already checking. This is a bog-standard form with two fields (username and password):

<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post"><fieldset>
<label><input type="text" name="name" id="name" /> Name</label><br />
<label><input type="password" name="pass" id="pass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</fieldset></form>

This will direct our user to the page we've been editing (using <?php echo $_SERVER['PHP_SELF']; ?>) with ?p=login appended — we'll use this to check if our form has been submitted so we can start processing our data. So, on we go, checking if this has been set:

if (isset($_GET['p']) && $_GET['p'] == "login") {
}

Inside this if statement we'll check our username and password against the values we set at the top of our file:

if (isset($_GET['p']) && $_GET['p'] == "login") {
   if ($_POST['name'] != $username) {
      echo "<p>Sorry, that username does not match. Use your browser back button to go back and try again.</p>";
      exit;
   } else if ($_POST['pass'] != $password) {
      echo "<p>Sorry, that password does not match. Use your browser back button to go back and try again.</p>";
      exit;
   }
}

So, that was the code to deal with incorrect data entry. Now we need to check for the correct data entry and set the cookie if everything is correct, right and funky:

if (isset($_GET['p']) && $_GET['p'] == "login") {
   if ($_POST['name'] != $username) {
      echo "<p>Sorry, that username does not match. Use your browser back button to go back and try again.</p>";
      exit;
   } else if ($_POST['pass'] != $password) {
      echo "<p>Sorry, that password does not match. Use your browser back button to go back and try again.</p>";
      exit;
   } else if ($_POST['name'] == $username && $_POST['pass'] == $password) {
      setcookie('MyLoginPage', md5($_POST['pass'].$randomword));
      header("Location: $_SERVER[PHP_SELF]");
   } else {
      echo "<p>Sorry, you could not be logged in at this time. Refresh the page and try again.</p>";
   }
}

Now we need to put ALL of these bits together:

<?php
$username = "user";
$password = "pass";
$randomword = "bibblebobblechocolatemousse";

if (isset($_COOKIE['MyLoginPage'])) {
   if ($_COOKIE['MyLoginPage'] == md5($password.$randomword)) {
?>

      CONTENT HERE
<?php
      exit;
   } else {
      echo "<p>Bad cookie. Clear please clear them out and try to login again.</p>";
      exit;
   }
}

if (isset($_GET['p']) && $_GET['p'] == "login") {
   if ($_POST['name'] != $username) {
      echo "<p>Sorry, that username does not match. Use your browser back button to go back and try again.</p>";
      exit;
   } else if ($_POST['pass'] != $password) {
      echo "<p>Sorry, that password does not match. Use your browser back button to go back and try again.</p>";
      exit;
   } else if ($_POST['name'] == $username && $_POST['pass'] == $password) {
      setcookie('MyLoginPage', md5($_POST['pass'].$randomword));
      header("Location: $_SERVER[PHP_SELF]");
   } else {
      echo "<p>Sorry, you could not be logged in at this time. Refresh the page and try again.</p>";
   }
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post"><fieldset>
<label><input type="text" name="name" id="name" /> Name</label><br />
<label><input type="password" name="pass" id="pass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</fieldset></form>

That's it! Put your content where "CONTENT HERE" is — this is where you need to put everything (including doctype, head, body, etc) because if we put any HTML output (this includes spaces, so make sure there are none before we open PHP for the first time) before our PHP our cookie won't set and we'll get errors. With that in mind, get making your own login page!

Tags: php, security, login,
Last Updated On: 01st March 06 by Jem
Bookmark At: StumbleUpon, Digg

tutorialtastic — ultimately better than pixelfx
Copyright © Jem Turner 2003-08. (About | Disclaimer | Link In)