Home arrow PHP arrow Page 3 - Creating a Membership System
PHP

Creating a Membership System


This well written article well help you create a membership system for your website using PHP and MySQL.

Author Info:
By: Eric 'phpfreak' Rosebrock
Rating: 5 stars5 stars5 stars5 stars5 stars / 141
March 27, 2003
TABLE OF CONTENTS:
  1. · Creating a Membership System
  2. · Page 1
  3. · Page 2
  4. · Summary

print this article
SEARCH DEVARTICLES

Creating a Membership System - Page 2
(Page 3 of 4 )

Activating the Membership

This next step is to create a script that based upon the email we have sent the user with their information, we can activate the account by just calling the script. Here's the script below:

<?
/* Account activation script */
// Get database connection
include 'db.php';
// Create variables from URL.
$userid = $_REQUEST['id'];
$code = $_REQUEST['code'];
$sql = mysql_query("UPDATE users SET activated='1' WHERE userid='$userid' AND password='$code'");
$sql_doublecheck = mysql_query("SELECT * FROM users WHERE userid='$userid' AND password='$code' AND activated='1'");
$doublecheck = mysql_num_rows($sql_doublecheck);
if($doublecheck == 0){
    echo "<strong><font color=red>Your account could not be activated!</font></strong>";
} elseif ($doublecheck > 0) {
    echo "<strong>Your account has been activated!</strong> You may login below!<br />";
    include 'login_form.html';
}
?>

We'll skip the first codeblock about the db.php because I explained it eariler to you. The codeblock we'll talk about first is where we break the variables up in the query string to individual variables for simple use.

// Create variables from URL.
$userid = $_REQUEST['id'];
$code = $_REQUEST['code'];

Let me take a moment for the n00bies out there and explain a query string. This is basically your script's file name ثنµْ followd by a ? (question mark) and then the variable name and it's value. Each string and it's value are seperated from another string and it's value with an & (AN) sign. For example, our query string is:

activate.php?id=(The user's id from the mysql_insert_id function)&code=(The user's encrypted pasword)

By using this query string, I broke the code up by treating it as a $_REQUEST variable found in the PHP Manual Predefined Variables section. If I were to post something from a form, I would have used the $_POST and etc..

So, I turned the query string into two variables, $userid and $code for my MySQL query.

$sql = mysql_query("UPDATE users SET activated='1' WHERE userid='$userid' AND password='$code'");

From this point, I pull a MySQL query and then change the "activated" column which was Enumerated with the settings of 0 and 1. 0 being not activated and 1 being activated. During this update query, I check the information by the user by two additional fields in the database, userid and the password field.

If all of these values are correct in the query string and they match a row in my database, the affected row will be changed to "activated=1" and the user can now login.

$sql_doublecheck = mysql_query("SELECT * FROM users WHERE userid='$userid' AND password='$code' AND activated='1'");
$doublecheck = mysql_num_rows($sql_doublecheck);
if($doublecheck == 0){
    echo "<strong><font color=red>Your account could not be activated!</font></strong>";
} elseif ($doublecheck > 0) {
    echo "<strong>Your account has been activated!</strong> You may login below!<br />";
    include 'login_form.html';
}
?>

This may seem reduntant to some people, or the wrong way of going about it, but to me this is the most strict method of checking to see if the row was actually updated properly and then giving the user the success or failed message. After my initial query of changing the activated column to 1 if the query string information was correct, I pull an additional query to doublecheck that it has definately been changed. We've already talked about the functions used here in previous code blocks.

As you can see, if the update was successful, we've simply displayed a small message and given the user the ability to enter his/her username and password to post to the next script.

Once again, all of these files are included in the soucecode file at the end of this tutorial.

The Login Verification

In the form that we displayed with the username and password fields, we will be posting to a file called "checkuser.php". This file is what really handles alot of the user processing after they have already registered and activated their membership. Let's take a look at this script now.

<?
/* Check User Script */
session_start();  // Start Session
include 'db.php';
// Conver to simple variables
$username = $_POST['username'];
$password = $_POST['password'];
if((!$username) || (!$password)){
    echo "Please enter ALL of the information! <br />";
    include 'login_form.html';
    exit();
}
// Convert password to md5 hash
$password = md5($password);
// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
    while($row = mysql_fetch_array($sql)){
    foreach( $row AS $key => $val ){
        $$key = stripslashes( $val );
    }
        // Register some session variables!
        session_register('first_name');
        $_SESSION['first_name'] = $first_name;
        session_register('last_name');
        $_SESSION['last_name'] = $last_name;
        session_register('email_address');
        $_SESSION['email_address'] = $email_address;
        session_register('special_user');
        $_SESSION['user_level'] = $user_level;
        mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");
        header("Location: login_success.php");
    }
} else {
    echo "You could not be logged in! Either the username and password do not match or you have not validated your membership!<br />
    Please try again!<br />";
    include 'login_form.html';
}
?>

Don't panic! It's not that bad either! Let's break it down now.

<?
/* Check User Script */
session_start();  // Start Session

Ahh.. sessions. My favorite! Here we started a PHP Session using session_start(). This is a very simple task but can go wrong very easily. You MUST (let me underline that and make it bold) MUST do this before anything is displayed to your web browser by the script you are starting a session with. If you don't do this, you'll start getting some ugly errors saying Headers already sent by.... blah blah. I can garuntee you that this is a problem and will mess your website up something ugly. Don't make me repeat that!

If you do not start the session at the top of each script you are wanting to use sessions on, you will not be able to use the session variables. I usually do this in a header.php file and call the header.php file at the top of each of my scripts along with the db.php and etc. You'll figure that out on your own.

// Convert to simple variables
$username = $_POST['username'];
$password = $_POST['password'];

Once again, this is my personal preference and I like to simplify my variables. You don't have to perform this step if you don't want to, just fix the code below.

if((!$username) || (!$password)){
    echo "Please enter ALL of the information! <br />";
    include 'login_form.html';
    exit();
}

You would not believe how many people will actually click the submit button on a form without typing something in. I don't know if it's hereditary or just something fun to do. The above code is simply a check to see if they did such a thing and give them the login form without executing the rest of the script first. Knuckleheads!

// Convert password to md5 hash
$password = md5($password);

Remember all of that stuff I was saying about passwords earlier? Well, this snipplet right here takes the human readable password (the one we emailed to the user) and then converts it to the md5 hashed version of the same password so we can check it inside the database and ensure that they match each other below:

// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
    while($row = mysql_fetch_array($sql)){
    foreach( $row AS $key => $val ){
        $$key = stripslashes( $val );
    }

This is the MySQL select query that checks the username and password match the one inside the database. This code block also returns the number of rows affected by the query and if the number is greater than zero (meaning that we have found a match because it would return 1) it will build the information we need in the rest of the script. If the $login_check variable is equal to zero, we'll simply present the login form again.

There's also something about this code block that I would like to point out. There's a chunck of code that will pull the information from your database and strip the slashes out of it and create a variable for each column inside your database that matches the row. This is a handly little snip that can save you tons of time when you need to stripslashes() a bunch of variables. Here's that exact snipplet by itself:

while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
    $$key = stripslashes( $val );
}

Let's say that I had 3 columns in my table. The first column being "first_name", second being "last_name" and third being "user_level". With this snipplet, I have just created $first_name, $last_name, and $user_level that has no backslashes in it and also have the values of the columns in the database. Pretty sweet eh? Good, thank php_rox the next time you see him on IRC :)

Back to the topic, here's the next code block

 // Register some session variables!
    session_register('first_name');
    $_SESSION['first_name'] = $first_name;
    session_register('last_name');
    $_SESSION['last_name'] = $last_name;
    session_register('email_address');
    $_SESSION['email_address'] = $email_address;
    session_register('special_user');
    $_SESSION['user_level'] = $user_level;

Ahh the mighty sessions again! This is very simple believe it or not. A lot of people have a really difficult time with sessions, but this script will hopefully show you how they work.

Let me take a moment to expalin sessions to those who don't understand them that well. I'm not expert but I may be able to give you the idea.

We are all pretty familiar with a cookie. It's a little text file that's stored on our computers that contain information about us and it's only readable by the website that the cookie was issued from (and our text editors).

It may contain such information such as our first name, email address or when our last visit was. Well, that's cool but guess what? Lately, web browser developers and other software developers have been making it very difficult for webmasters to set cookies anymore. The cookie reliability rate has dropped dramatically because of security levels and cookie blocking programs out there. PHP has fixed this for us.

A session is similar to a cookie, but instead of storing such information on the user's hard drive, it stores it on the server in a temporary directory instead. This cookie is assigned a special number and so is the session that the user has. If the session ID and the temporary file ID are the same, the webserver will access the session cookie on it's hard drive.

This gives webmasters alot of room to expand the functionality of their websites and it makes life easier becuase to my knowledge, the user can't block a session from being started. Oh, and when the user closes his web browser the temporary cookie is destroyed from the webserver. Got it? Hope so :)

The first thing we're going to do is create a session variable. We do this by registering a name to it:

session_register('first_name');

Then we assign that session variable name a value:

$_SESSION['first_name'] = $first_name;

So if the user's name was "Eric" our session value named "first_name" would become "Eric". In other words: $_SESSION['first_name']; would be "Eric" for this particular user!

The really cool thing about this is we can use this in many places on our website without querying the database anymore because we just registered it as a session. Just remember, each time we want to call a session variable, we MUST have session_start() at the top of that script.

Next please :)

mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'"); 
   header("Location: login_success.php");
   }


Alrighty, we've got a column in our database that we can use called "last_login" and it's of DATETIME column type. Since the user has been validated and everything is working as planned, we can now update the user's information and set the last_login column to a date that is equivalent to this very moment using the "now()" function.

You may be wondering why I chose to update the login_date on their membership. Well, later on let's say that our user database grows into the hundreds of thousands. Now my database is getting pretty large. I can create a script that can run every month to determine if a user has logged into the website sometime in the last 6 months. If they have, I'll leave their membership.

If they haven't I can delete their membership or even send them an email notifying them that I am about to delete their membership and therefore I change the activated value back to 0 and send them a link to reactivate it. If they don't activate it within 30 days, I'll delete it. This is completely optional, but it's a nice feature to build in. No, I won't show you how to do that :)

Ahh.. the header("Location: login_success.php"); Why did I do this? This is because I want to double check that the sessions have been stored properly. It's bascially the same thing as a Meta Refresh in HTML terms, execpt the PHP script will automatically direct you to the page in this header() function. Once again, just as session_start() this is one of "those" functions that must be called before any HTML is echoed to the user's browser.

Next block..

} else {
    echo "You could not be logged in! Either the username and password do not match or you have not validated your membership!<br />
    Please try again!<br />";
    include 'login_form.html';
}
?>

Call this what you want it to, i.e: bad coding habbits or whatever, but I'll just say that this is the end of the error checking of the mysql_query. If no rows were found in the $login_check variable above, we'll simply give them this error and include the login form again.

Well, that's it for this script. We've either successfuly validated the user against the database and redirected them to our next script or we've given them a login form to try again.

Let's view last script for the login process.

Login Success Script

This script is the final phase of our login. If everything has gone well up to this point, we can show the user a success message that uses their session variables that we registered when they logged in. This script will also give you an introduction to user groups and access levels on your website.

Here's the script.

<?
session_start();
echo "Welcome ". $_SESSION['first_name'] ." ". $_SESSION['last_name'] ."!
    You have made it to the members area!<br /><br />";
echo "Your user level is ". $_SESSION['user_level']." which enables
    you access to the following areas: <br />";
if($_SESSION['user_level'] == 0){
    echo "- Forums<br />- Chat Room<br />";
}
if($_SESSION['user_level'] == 1){
    echo "- Forums<br />- Chat Room<br />- Moderator Area<br />";
}
echo "<br /><a href=logout.php>Logout</a>";
?>

Let's break it down!

<?
session_start();
echo "Welcome ". $_SESSION['first_name'] ." ". $_SESSION['last_name'] ."!
    You have made it to the members area!<br /><br />";
echo "Your user level is ". $_SESSION['user_level']." which enables
    you access to the following areas: <br />";

This starts the session as I have described in previous pages and then gives the user a welcome message with their first name, last name. It also precludes to which sections they have access to based upon the user_level setting in the database. See below.

if($_SESSION['user_level'] == 0){
    echo "- Forums<br />- Chat Room<br />";
}
if($_SESSION['user_level'] == 1){
    echo "- Forums<br />- Chat Room<br />- Moderator Area<br />";
}

Here we are checking the level that the user has access to and showing them the links. By now, this should be pretty easy to figure out. Basically "If your user_level = 0 you have access to Forums and Chat Room" or "If your user_level is 1 you have access to Forums, Chat Room and the Moderator Area".

echo "<br /><a href=logout.php>Logout</a>";
?>

This is the logout link to the next script.

The Logout Script

<?
session_start();
if(!isset($_REQUEST['logmeout'])){
    echo "<center>Are you sure you want to logout?</center><br />";
    echo "<center><a href=logout.php?logmeout=true>Yes</a> |
    <a href=javascript:history.back()>No</a>";
} else {
    session_destroy();
    if(!session_is_registered('first_name')){
        echo "<center><font color=red><strong>You are now logged
            out!</strong></font></center><br />";
        echo "<center><strong>Login:</strong></center><br />";
        include 'login_form.html';
    }
}
?>


Ok, I have finally used isset() variable. Here all I am doing is checking that the $logmeout variable is not set. If it isn't, I'll ask the user if they are sure they want to logout and give them two options.

The "Yes" option includes a query string back to the same script that has the $logmeout variable built inside of it and then passes the first if statement which destroys their session logging them out with the session_destroy() function and including the login form. They will no longer be logged in!

The only thing that I haven't covered is how to generate a lost password recovery tool. Let's do this and then I'll wrap up this tutorial so yot">n be on your way to making your website a community!

The Lost Password Utility

This is a vital tool for you to have because you won't be able to tell the users what their password is using the md5 encrypted passwords. Besides, emailing someone their password each time they need it would really suck. Let's keep it all automated!

Here's the script I would use:

<?
include 'db.php';
switch($_POST['recover']){
    default:
    include 'lost_pw.html';
    break;
    case "recover":
    recover_pw($_POST['email_address']);
    break;
}
function recover_pw($email_address){
    if(!$email_address){
        echo "You forgot to enter your Email address
            <strong>Knucklehead</strong><br />";
        include 'lost_pw.html';
        exit();
    }
    // quick check to see if record exists    
    $sql_check = mysql_query("SELECT * FROM users WHERE email_address='$email_address'");
    $sql_check_num = mysql_num_rows($sql_check);
    if($sql_check_num == 0){
        echo "No records found matching your email address<br />";
        include 'lost_pw.html';
        exit();
    }
    // Everything looks ok, generate password, update it and send it!
    function makeRandomPassword() {
          $salt = "abchefghjkmnpqrstuvwxyz0123456789";
          srand((double)microtime()*1000000); 
          $i = 0;
          while ($i <= 7) {
                $num = rand() % 33;
                $tmp = substr($salt, $num, 1);
                $pass = $pass . $tmp;
                $i++;
          }
          return $pass;
    }
    $random_password = makeRandomPassword();
    $db_password = md5($random_password);
    $sql = mysql_query("UPDATE users SET password='$db_password'
                WHERE email_address='$email_address'");
    $subject = "Your Password at MyWebsite!";
    $message = "Hi, we have reset your password.
    New Password: $random_password
   
http://www.mywebsite.com/login.php

    Thanks!
    The Webmaster
    This is an automated response, please do not reply!";
    mail($email_address, $subject, $message, "From: MyDomain Webmaster<
admin@mydomain.com>\n
        X-Mailer: PHP/" . phpversion());
    echo "Your password has been sent! Please check your email!<br />";
    include 'login_form.html';
}
?>

For this script, we created a lost_pw.html form which obtains the user's email address from their input. It also has a hidden field called "recover" with a value of "recover". At the top of this script I created a switch which is another method of validating information instead of using an if else statement.

We gathered the info, queried the database and found determined if we found a match. If we did, we sent the user's email a newly generated random password and updated the database with that information. Then we displayed the login form and told the user to check his/her email address for the new password.

If no email address match was found, we simply told the user and presented the lost password form again. If they didn't enter an email address, we called them a Knucklehead and told them to enter their email address in the form below.

Let's summarize on the next page.


blog comments powered by Disqus
PHP ARTICLES

- Removing Singletons in PHP
- Singletons in PHP
- Implement Facebook Javascript SDK with PHP
- Making Usage Statistics in PHP
- Installing PHP under Windows: Further Config...
- File Version Management in PHP
- Statistical View of Data in a Clustered Bar ...
- Creating a Multi-File Upload Script in PHP
- Executing Microsoft SQL Server Stored Proced...
- Code 10x More Efficiently Using Data Access ...
- A Few Tips for Speeding Up PHP Code
- The Modular Web Page
- Quick E-Commerce with PHP and PayPal
- Regression Testing With JMeter
- Building an Iterator with PHP

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials