Search This Blog

Monday, June 13, 2011

Creating a User Registration Script

Ready to welcome users to your system? If you plan to build a Web site that requires user membership, you'll want to provide some means for new users to register. Here's a garden variety registration script that will step you through the following procedures:
  1. Display a "Terms Of Use" page: a user is obliged to agree with these terms if he wants to register as a member.
  2. Present one or more registration forms requesting necessary information.
  3. Create the user's account: create a new record in the user table and insert relevant information.
  4. Let the user know that his membership account has been created.
  5. Send a confirmation e-mail to the user's address (part of the information the new user provided when he registered).
To keep the focus on the data aspect of this application, we won't implement the first step (which is just a matter of how you grant access to the actual registration form) or the last step here. Of course, you can always add to the basic application later.

register.php

Creating a new user account involves creating a new entry in the primary key in the user table, which must then be used across all the tables recording the user's activities at your site. The account is also used for authenticating the user when he attempts to enter a password-protected area of your site. So an account comprises both a user ID and a password.
Nothing stops you from saving user passwords as plain text for all to see, but encrypted passwords do provide better security, so that's what you'll do here.

Here's the source code of the user registration script register.php. It'll be explained as you go along. To begin with, include the common_db.inc file:

<?php
//register.php
include_once " ./common_db.inc";

in_use()

The in_use() function queries the MySQL server about whether the typed-in userid is already in use, and returns 1 if it is:

function in_use($userid)
{
   global $user_tablename;
   $query = "SELECT userid FROM $user_tablename WHERE userid = '$userid'";
   $result = mysql_query($query);
   if(!mysql_num_rows($resul t)) {
       return 0;
   }else{
      return 1;
   }
}

register_form()

The register_form() function displays the form into which a user types in his membership details. You begin by connecting to the database and finding out which positions you can present as options to prospective players who want to be involved in the sport:

function register_form()
{
   global $userposition;
   global $PHP_SELF;

   $link _id = db_connect();
   mysql_select = db( "sample_db");
   $postion_array = enum_options('userposition', $link_id);
   mysql_close($link_id);
?>

The array $position_array now holds all the positions from which the user can choose. Next, you create the table that will serve as the interface for the users—notice the use of the POST method for this example:

<center><H3>Create your account! </H3></center>
<form method="post" actions "<?php echo $PHP_SELF ?>">
<Input type="hidden" name="action">
  <div align="center"><center><table border="1" width="90%">
  <tr>
    <th width="30%" nowrap>Desired ID</th>
    <td width="70%"><input type="text" name="userid"
                           size="8" maxlength="8"></td>
  </tr>
  <tr>
    <th width="30%" nowrap>Desired Password</th>
    <td WlDTH="70%"><input type= "password"
                           name="userpassword" size="15"></td>
  </tr>
  <tr>
    <th width="30%" nowrap>Retype Password</th>
    <td width="70%"><input type= "password"
                           name="userpassword2" size="15"></td>
  </tr>
  <tr>
    <th width="30%" nowrap>Full Name</th>
    <td width="70%"><input type="text" name="username" size="20"></td>
  </tr>
  <tr>
    <th width="30%" nowrap>Position</th>
    <td width="70%"><select. name="userposition" size="1">
<?php

There are two password fields rather than one. Because you specify TYPE = "PASSWORD", the value entered is masked by asterisks, so that not even the user can see what he's typing in. Having him type it in twice will catch any mistyping later when you check that the two values match.

The userposition drop-down menu is constructed on-the-fly from the values held in the $position_array variable, which you populated at the beginning of the function:

  for($i=0; $i < count($position_array); $i++)
     if(!isset($userposition) && $i == 0) {
        echo "<OPTION SELECTED VALUE=\"". $position_array[$i] .
        "\">" . $position_array[$i] . '</OPTION>\n";
     }else if($userposition =- $cposition_array[$i]) {
        echo "<OPTION SELECTED VALUE=\"" . $position_array[$i] . "\">".
        $position_array[$i] . "</OPTION>\n";
     }else{
        echo "<OPTION VALUE=\"". $position_array[$i] . "\">" .
        $position_array [$i] . "</OPTION>\n";
     }
  }
?>

Now you continue with the other options in the table:

      </select></td>
    </tr>
    <tr>
      <th width="30%" nowrap>Email</th>
      <td width="70%"><input type="text" name="useremail" size="20"
      </td>
    </tr>
    <tr>
      <th width="30%" nowrap>Profile</th>
      <td WIDTH=70%"><textarea rows="5" cols="40"
                               name="userprofile"></textarea></tr>
    </tr>
    <tr>
      <th width="30%" colspan="2" nowrap>
        <input type="submit" value="Submit">
        <input type="reset" value="Reset"></th>
    </tr>
  </table>
  </center></div>
<form>
<?php
}

create_account()

The create_account() function inserts the new record into the user table. It can be called only when the Submit button created in register_form() is clicked. As a result, you know that the $_POST array will be populated, and you can use those values like so:

function create_account()
{
   $userid = $_POST['userid'];
   $username = $-POST['username'];
   $userpasaword = $_POST['userpassword'];
   $userpassword2 = $_ POST ['userpassword'];
   $userposition $_POST ['userposition'];
   $useremail = $_POST|'useremail'];
   $userprofile = $_POST['userprofile'];

   global $delfault_dbname, $user_tablename;
The user-submitted values are verified, to check that what's been entered correctly:
if(empty($userid)) {
   error_ message("Enter your desired ID!");
}
if(empty($userpassword)) {
   error_message["Enter your desired password!");
}
if(strlen($userpassword) < 4 ){
   error_message("Password too short!");
}
if(empty($userpassword2)) (
   error_message("Retype your password for verification!");
}
if(empty($username)){
   error_message("Enter your full. name!");
}
if(empty($username)) {
   error_mesage("Enter your email address!");
}
if(empty($userprofile)){
   $userprofile = "No Comment.";
}

if($userpassword != $userpassword2){
   error_message("Your desired password and retyped password mismatch!");
}

Then, make a connection to the database and call the in_use() function to verify that the userid is unique (because it is the primary key):

$link_id = db_connect($default_dbname);

if(in_use($userid) ){
   error_message("$userid is in use. Please choose a different ID.");
}

When querying to insert a new user's details, you pass NULL to usernumber to auto-increment it. You also use the password() server function to encrypt the user-specified password:

$query = "INSERT INTO user. VALUES(NULL, '$userid', password('$userpassword'),
                  '$username', '$userposition', '$useremail', '$userprofile')";
$result = mysql_query($query);
if(!$result){
   error_message(sgl_error());
}
You report the newly incremented user number with mysql_insert_id():

   $usernumber = mysql_insert_id($link_id);
   html_header();
?>
And you display a table showing the user his membership information:
<center><h3>
<?php echo $username ?>; thank you for registering with us!
</h3></center>

<div align="center"><center><table border="1" width="90%">
  <tr>
    <th width="30%" nowrap>User Number</TH>
    <td width="70%"><?php echo $usernumber ?></td> </tr>
  <tr>
    <th width="30%" nowrap>Desired ID</th>
    <td width="70%"><?php echo $userid '?></td> </tr>
  <tr>
    <th width="30%" nowrap>Desired Password</th>
    <td width="70%"><?php echo $userpassword ?></td>
  </tr>
  <tr>
    <th width="30%" nowrap>Full Name</th>
    <td width="70%"><?php echo $username ?></td>
  </tr>
  <tr>
    <th width="30%" nowrap>Position</th>
    <td width="70%"><?php echo $userposition ?></td>
  </tr>
  <tr>
    <th width="30%" nowraP>Email</th>
    <td width="70%"><?php echo $usermail ?></td>
  </tr>
  <tr>
    <th width="30%" nowrap>Profile]</th>
    <td with="70%"><?php echo htmlspecialchars($userprofile) ?></td>
  </tr>
</table>
</center></div>
<?php
    html.footer();
}

Choosing Actions to Take

Finally, you use action to specify the appropriate functions to call. In case $_POST is unset, give it a default value that takes you to the registration_form() function:

If(empty($_POST)){
   $_POST[' action,']="";
}
switch($_POST['action']) {
   case "register";
      create_account();
   break;
   default:
      html_header();
      register_form();
      html_footer();
   break;
}
?>

Let's see how that looks in action. First, register_form() displays a form into which the user can enter his details.

The user can then fill in his details as he sees fit. As the last step, the script displays a thank you note plus a table showing the information the user entered and that was used to create his account. 

You should note that it's not a good idea to display a user's password like this. A relatively secure way to confirm this information is to include it in an e-mail sent to the user's specified account.

Now you've seen how you can use PHP to add members to your database, and therefore the site. Obviously, if you wanted to build on this, or integrate it into your own site, you may want to add extra buttons to take you to different pages once you've confirmed a user's registration. This, however, suffices for the example.

Now let's move on to see how you can record users' accesses to your site.