Home arrow PHP arrow Page 2 - 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 1
(Page 2 of 4 )

Create the Database Structure

Let's begin by creating a standard database structure for you to use. First, you may use phpMyAdmin or something that you are familiar with to create your databases. I use phpMyAdmin because it's fairly easy to use and I don't have to store any applications or use any command line stuff while on my computer. Simply create your own database and call it whatever you want. Inside that database, run this SQL statement.

CREATE TABLE users (
  userid int(25) NOT NULL auto_increment,
  first_name varchar(25) NOT NULL default '',
  last_name varchar(25) NOT NULL default '',
  email_address varchar(25) NOT NULL default '',
  username varchar(25) NOT NULL default '',
  password varchar(255) NOT NULL default '',
  info text NOT NULL,
  user_level enum('0','1','2','3') NOT NULL default '0',
  signup_date datetime NOT NULL default '0000-00-00 00:00:00',
  last_login datetime NOT NULL default '0000-00-00 00:00:00',
  activated enum('0','1') NOT NULL default '0',
  PRIMARY KEY  (userid)
) TYPE=MyISAM COMMENT='Membership Information';

Before I continue, I must say this. You may or may not agree with my column types in this example above. That's ok, it's not your database so please refrain from complaining about it. There is nothing wrong with these column types that will stop it from working like we want it to. Yes, I have had people complain about my databases structures before.

Now that you have created your database and you are ready to move on, let's start on collecting information about the user.

User Signup - Collecting the Data

Now that we've created a database and we're ready to move on to collecting information about this database. The first thing you want to do is create an information collection form. You can do this simply by using your favorite html editor, in my case either by hand or using DreamweaverMX. Don't worry, I'll include an example form along with all of the scripts you need in the sourcecode file with this tutorial. You can download it on the last page of this tutorial.

Our input form will look something like this:

First Name
Last Name
Email Address
Desired Username
Information about you:
 

This will gather enough information about the user for our purpose. You can always add more fields to the scripts in this tutorial, so don't worry!

This form will post to a script called register.php and will do a few things that are essential. We'll put some basic error checking with PHP. I am not including any special Error checking functions on this form because everyone likes to do error checking their own way. I'll basically be checking that the user entered the required fields of this form and if they didn't, we'll put an error message on the page that they post this form to.

Note: Personally, I like to keep HTML where it belongs. As much as possible, I'll try to save HTML files in a specific directory on my web server and include them where necessary. So, I've saved this form in an HTML file on my server and I'll include it in my register.php where the error checking goes.

Let's look at the script that this form will post.

User Signup - Error Checking & Creating the Membership

The form you seen on the last page will actually post to a script called register.php. This script is shown below:

<?
include 'db.php';
// Define post fields into simple variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_address = $_POST['email_address'];
$username = $_POST['username'];
$info = $_POST['info'];
/* Let's strip some slashes in case the user entered
any escaped characters. */
$first_name = stripslashes($first_name);
$last_name = stripslashes($last_name);
$email_address = stripslashes($email_address);
$username = stripslashes($username);
$info = stripslashes($info);
/* Do some error checking on the form posted fields */
if((!$first_name) || (!$last_name) || (!$email_address) || (!$username)){
    echo 'You did not submit the following required information! <br />';
    if(!$first_name){
        echo "First Name is a required field. Please enter it below.<br />";
    }
    if(!$last_name){
        echo "Last Name is a required field. Please enter it below.<br />";
    }
    if(!$email_address){
        echo "Email Address is a required field. Please enter it below.<br />";
    }
    if(!$username){
        echo "Desired Username is a required field. Please enter it below.<br />";
    }
    include 'join_form.html'; // Show the form again!
    /* End the error checking and if everything is ok, we'll move on to
     creating the user account */
    exit(); // if the error checking has failed, we'll exit the script!
}
/* Let's do some checking and ensure that the user's email address or username
does not exist in the database */
 $sql_email_check = mysql_query("SELECT email_address FROM users 
            WHERE email_address='$email_address'");
 $sql_username_check = mysql_query("SELECT username FROM users 
            WHERE username='$username'");
 $email_check = mysql_num_rows($sql_email_check);
 $username_check = mysql_num_rows($sql_username_check);
 if(($email_check > 0) || ($username_check > 0)){
    echo "Please fix the following errors: <br />";
    if($email_check > 0){
        echo "<strong>Your email address has already been used by another member
        in our database. Please submit a different Email address!<br />";
        unset($email_address);
    }
    if($username_check > 0){
        echo "The username you have selected has already been used by another member
         in our database. Please choose a different Username!<br />";
        unset($username);
    }
    include 'join_form.html'; // Show the form again!
     exit();  // exit the script so that we do not create this account!
 }
/* Everything has passed both error checks that we have done.
It's time to create the account! */
/* Random Password generator.
http://www.phpfreaks.com/quickcode/Random_Password_Generator/56.php
We'll generate a random password for the
user and encrypt it, email it and then enter it into the db.
*/
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);
// Enter info into the Database.
$info2 = htmlspecialchars($info);
$sql = mysql_query("INSERT INTO users (first_name, last_name,
        email_address, username, password, info, signup_date)
        VALUES('$first_name', '$last_name', '$email_address',
        '$username', '$db_password', '$info2', now())") 
        or die (mysql_error());
if(!$sql){
    echo 'There has been an error creating your account. Please contact the webmaster.';
} else {
    $userid = mysql_insert_id();
    // Let's mail the user!
    $subject = "Your Membership at MyWebsite!";
    $message = "Dear $first_name $last_name,
    Thank you for registering at our website,
http://www.mydomain.com!
    You are two steps away from logging in and accessing our exclusive members area.
    To activate your membership,
    please click here:
http://www.mydomain.com/activate.php?id=$userid&code=$db_password
    Once you activate your memebership, you will be able to login
    with the following information:
    Username: $username
    Password: $random_password
    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 membership information has been mailed to your email address!
    Please check it and follow the directions!';
}
?>

Don't worry, we'll begin talking about this script and explaining what all of this does now.

Let's start at the beginning.

<?
include 'db.php';

This code simply includes a script that I wrote that includes my database connection on a mysql_pconnect function. The reason I put this here is so that I don't have to continuously write out the database information every time I need it. PHP's include functions work great and can really save you a lot of time from writing out code over and over again. The mysql_pconnect function allows you to establish a persistent connection with the database.

What is a persistent connection? It's basically a way to reuse MySQL threads over and over again without starting a new instance of MySQL to handle each connection. Let's say you were browsing my site and you started a MySQL thread and then you left the site for awhile. Then, I came in and started browsing the website. I could actually pick up your MySQL thread and start using it instead of starting a new thread. This dramatically reduces the MySQL load on your server.

An example of how to establish a MySQL Persistent connection can be found here. The db.php file is written off of the code example found in that link.

Ok.. we've got the database stuff figured out. Let's move on to the next section of the script.

// Define post fields into simple variables
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_address = $_POST['email_address'];
$username = $_POST['username'];
$info = $_POST['info'];
/* Let's strip some slashes in case the user entered
any escaped characters. */
$first_name = stripslashes($first_name);
$last_name = stripslashes($last_name);
$email_address = stripslashes($email_address);
$username = stripslashes($username);
$info = stripslashes($info);

These first section of code block simply convert the register_globals fields to simple variables for use in this script. This is my preference and I prefer to do that instead of typing out the full string each time I need to use it. You'll see that it can save you alot of effort.

The second code block will strip the slashes out of the user's posted fields. It uses the stripslashes() function which removes the backslashes ( \ ) found before each ' and " that PHP automatically adds to the posted fields. We do this because we might need to display the information that the user posts in the form if we find any errors in the error checking code below.

/* Do some error checking on the form posted fields */
if((!$first_name) || (!$last_name) || (!$email_address) || (!$username)){
    echo 'You did not submit the following required information! <br />';
    if(!$first_name){
        echo "First Name is a required field. Please enter it below.<br />";
    }
    if(!$last_name){
        echo "Last Name is a required field. Please enter it below.<br />";
    }
    if(!$email_address){
        echo "Email Address is a required field. Please enter it below.<br />";
    }
    if(!$username){
        echo "Desired Username is a required field. Please enter it below.<br />";
    }
    include 'join_form.html'; // Show the form again!
    /* End the error checking and if everything is ok, we'll move on to
     creating the user account */
    exit(); // if the error checking has failed, we'll exit the script!
}

The code block above is actually very simple. It may look intimidating if you aren't very familiar with PHP, but trust me it's not that difficult to figure out. All this does is checks that each of the variables have something inside them. If not, we'll tell the user that they posted an empty field and they need to fill this back in. I'll verbalize the first row for you:

"If you did not enter anything in the first name field or you did not enter anything in the last_name field or you did not enter anything in the email address field or you did not enter anything in the username filed, I'll give you this error"

I hope that makes sense, because that's the way you need to verbalize it in your head. Using the || which also stands for "OR" is called a Bitwise Operator and it can be used to evaluate strings for your scripts.

Here's something that I would like to add. There's several ways to check if a string is empty. I am aware of that! Here's a couple.

if(!isset($string); or if(empty($string);

Using the isset() function or empty() function are up to you. I just check the ! (not bitwise operator) and it works fine for me.

Ok, some more about the code block above. If you examine the structure of it, you'll see that we will only display the applicable error. Once the error has been displayed, we'll give the user the form again and we'll fill in the applicable fields that they have already filled in. We do this by adding a value="<? echo $variable; ?> to the form input tag in the html.

The next function we used in this code block is the exit() function. This function will output an error message if you tell it to, and then exit the script without further execution of the code below it. I've found this is much easier than using one log if else statement to check the entire script for validity. Keep in mind, if you use a global footer.php file, you'll probably want to include this above the exit() function call or the bottom of your website may be cut off.

Next we'll do some checking inisde the database to ensure that we don't create a duplicate entry:

/* Let's do some checking and ensure that the user's email address or username
does not exist in the database */
 $sql_email_check = mysql_query("SELECT email_address FROM users WHERE email_address='$email_address'");
 $sql_username_check = mysql_query("SELECT username FROM users WHERE username='$username'");
 $email_check = mysql_num_rows($sql_email_check);
 $username_check = mysql_num_rows($sql_username_check);
if(($email_check > 0) || ($username_check > 0)){
    echo "Please fix the following errors: <br />";
    if($email_check > 0){
        echo "<strong>Your email address has already been used by another member
        in our database. Please submit a different Email address!<br />";
        unset($email_address);
    }
    if($username_check > 0){
        echo "The username you have selected has already been used by another member
        in our database. Please choose a different Username!<br />";
        unset($username);
    }
    include 'join_form.html'; // Show the form again!
     exit();  // exit the script so that we do not create this account!
 }

The above code checks the information that the user submitted and ensures that the email address and the username do not exist in the database already. If it does, we'll present the user with the form and have them enter a different value. This code block uses the unset() function which will remove the string $email_address and $username from PHP and it will in turn empty the form fields for those areas. Next, we'll prevent the script from going any furhter with the exit() function.

We also used a PHP/MySQL function to do our error checking called mysql_num_rows This function returns the number of rows found in the mysql_query that validate the set of circumstances we gave the mysql_query() function. Based upon that number, we can run some if statements and execute a certain set of commands we want to. You may find this very useful in your future scripts, so keep it in mind!

Let's go ahead and talk about the next block of code:

/* Random Password generator.
http://www.phpfreaks.com/quickcode/Random_Password_Generator/56.php
We'll generate a random password for the
user and encrypt it, email it and then enter it into the db.
*/
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);

This code uses a Random Password generator which creates a 7 character random password and then sends it to the user while encrypting it with the md5() hash function and stores it into the database along with the user's information.

This code block serves a few purposes. The first one being that we don't want to give the ability to create their own password right away. We want to validate this user in some way, so we'll prevent them from creating their own backdoor into our site. Then, we'll encrypt the password using the md5 function which is one way encryption. You won't be able to decrypt it yourself. The only way to validate the md5 from the database is to encrypt whatever you type in and then check to see if the two fields equal each other.

Next code block please :)

// Enter info into the Database.
$info2 = htmlspecialchars($info);
$sql = mysql_query("INSERT INTO users (first_name, last_name, email_address,
        username, password, info, signup_date)
    VALUES('$first_name', '$last_name', '$email_address',
        '$username', '$db_password', '$info2', now())") or die (mysql_error());
if(!$sql){
    echo 'There has been an error creating your account. Please contact the webmaster.';
} else {
    $userid = mysql_insert_id();
    // Let's mail the user!
    $subject = "Your Membership at MyWebsite!";
    $message = "Dear $first_name $last_name,
    Thank you for registering at our website,
http://www.mydomain.com!
    You are two steps away from logging in and accessing our exclusive members area.
    To activate your membership, please click here:
   
http://www.mydomain.com/activate.php?id=$userid&code=$db_password
    Once you activate your memebership, you will be able to login with the following 
    information:
    Username: $username
    Password: $random_password
    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 membership information has been mailed to your email address!
     Please check it and follow the directions!';
}
?>

The beautiful thing about developing advanced web applications is that you can make things look more complicated than they really are. The above code block simply inserts the user's information that they posted along with the random encrypted password that we generated into the database and then emails the user a special link.

A couple of the functions we used here are mysql_error() which is very useful in determining what went wrong with your MySQL query. It will return specific information from the MySQL server that will tell you what went wrong with your query. Another great PHP and MySQL function is mysql_insert_id() this function will tell you what the number was assigned to the row you just created by the auto_increment primary key, which is kind of important right now.

We've also just tapped on the mail() function of PHP. While this tutorial is not designed to teach you everything about each function we use, our use of this mail() function is to send an email to the person confirming their email address and giving them a link to validate themselves on our server. We'll cover the specifics of the validation later on. Here's an example of the email that will be sent to your users:


From: MyDomain Webmaster
To: you@email.com
Subject: Your Membership at MyWebsite!

Dear Eric Rosebrock,
Thank you for registering at our website, http://www.mydomain.com!

You are two steps away from logging in and accessing our exclusive members area.

To activate your membership, please click here: http://www.mydomain.com/activate.php?id=3&code=969f8a1a7247ec82769e837c2f853450

Once you activate your memebership, you will be able to login with the following information:
Username: myusername
Password: msxsag4h

Thanks!
The Webmaster

This is an automated response, please do not reply!


You may be wondering why I sent the user an email with the encrypted password as the $code variable in the query string. Well, as I said before it doesn't really matter because 1) md5 can't be decrypted (easily anyways) and 2) it gives me a method of validating the user in the next script. The user probably won't know what the hell that md5 junk is anyways. You may be wondering if I just comprimised my website. No, not really. You can always give the user a method of changing his/her password immediately after the first login if you are that worried about it. Besides, the user can't paste his encrypted password into the login form because the only thing that will happen is that mumbo jumbo will get encrypted again therefore invalidating his/her login. Trust me, it's safe.

Well, we've done it! If everything is working so far, which it is on my test server, we're ready to create the validation script. It only gets easier from here. That first script was pretty long and from here on it becomes a sinch to do.

Next: Page 2 >>

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