Thursday, November 6, 2008

creating a fully featured registration script

PHP web Development

In this tutorial you will learn how to create a fully featured registration script, users will be able to enter your site, visit the registration page, fill in the info, submit the form, receive an activation e-mail and be able to activate there accounts.

Alright, this tutorial won't teach you anything about design, so the finalized script won't look pretty at all, but it is very easy to implement into any design.

First, we are going to need to create a table in our database so that we can store all of our registration info. We are going to call this table, users since that's what it will store!

MySQL:
  1. CREATE TABLE users (
  2. id INT(11) NOT NULL AUTO_INCREMENT,
  3. username VARCHAR(30) NOT NULL,
  4. password CHAR(40) NOT NULL,
  5. email VARCHAR(70),
  6. active CHAR(32),
  7. PRIMARY KEY(id)
  8. );

That little SQL creates our table to store all of our user information in, now we need a way to connect to the database.

PHP:

  1. // CHANGE THESE VALUES
  2. DEFINE ('DB_USER', 'database username');
  3. DEFINE ('DB_PASSWORD', 'database password');
  4. DEFINE ('DB_HOST', 'localhost');
  5. DEFINE ('DB_NAME', 'database name');

  6. $dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error());

  7. @mysql_select_db (DB_NAME) OR die('Could not select the database: ' . mysql_error() );
  8. ?>

This is just a file that we can use to connect to our database with, now all we need to do is include it any file that we want to query the database from.

Now that we have our table and mysql connection file setup, we need to create the PHP file that allows the person to register.

Let's start off by creating the form processing part of the file, it will be included in the same file as the form.

PHP:

  1. if (isset($_POST['submitted'])) {

  2. $errors = array();
  3. require_once ('mysql_connect.php');

This part is easy, all it does is start a new PHP section, then our first if() statement is saying IF our form is submitted, then continue. We also start a new variable, and assign an array to it. So that we can echo out our errors (if there are any) at the end. We also include our mysql_connect.php file, since we will be querying the database.

PHP:
  1. if (eregi('^[[:alnum:]\.\'\-]{4,30}$', stripslashes(trim($_POST['username']))) ) {
  2. $user = mysql_real_escape_string($_POST['username']);
  3. $query = "SELECT username FROM users WHERE username = '$user'";
  4. $result = @mysql_query($query);
  5. $num = @mysql_num_rows($result);

  6. if ($num> 0) {
  7. $errors[] = 'The username you have chosen has already been taken, please try again.';
  8. } else {
  9. $username = mysql_real_escape_string($_POST['username']);
  10. }
  11. } else {
  12. $errors[] = 'Please provide a valid username between 4 and 30 characters.';
  13. }

This is where we check our first field, the username field. We use regular expressions to validate that the username is good. It must only contain numbers, letters, periods and it must be between 4 and 30 characters. If our regular expressions passes all the tests, we query the database and check if the username has been taken, if it has been taking we add an error to our $error array. If it is not taken then we it is assigned to the $username variable.

**UPDATE V1.1** - I have fixed the error that so many people are getting, I made a mistake, I have now added extra security to the script and it should be pretty much bug free.

PHP:
  1. if (!eregi('^[a-zA-Z]+[a-zA-Z0-9_-]*@([a-zA-Z0-9]+){1}(\.[a-zA-Z0-9]+){1,2}', stripslashes(trim($_POST['email'])) )) {
  2. $errors[] = 'Please provide a valid email address.';
  3. } else {
  4. $email = mysql_real_escape_string($_POST['email']);
  5. }

This little tid-bit of code just validates there e-mail address using another regular expression.

PHP:
  1. if (!empty($_POST['password1'])) {
  2. if ($_POST['password1'] != $_POST['password2']) {
  3. $errors[] = 'The 2 passwords you have entered do not match.';
  4. } else {
  5. $password = $_POST['password1'];
  6. }
  7. } else {
  8. $errors[] = 'Please provide a password.';
  9. }

This is where we validate our password(s). First we check if they entered in the first password, then if it isn't empty, we make sure that password 1 and password 2 are the exact same (password, and verify password). If they do not match each other, we add an error to our $errors array. If they do match each other, we continue.

PHP:
  1. if (empty($errors)) {
  2. $a = md5(uniqid(rand(), true));
  3. $query = "INSERT INTO users (username, email, password, active) VALUES ('$username', '$email', SHA('$password'), '$a')";

  4. $result = @mysql_query($query);

  5. if (mysql_affected_rows() == 1) {

  6. // Send the E-Mail
  7. $body = "Thank you for registering at the User Registration site. To activate your account, please click on this link:\n\n";
  8. $body .= "http://www.whateveraddressyouwanthere.com/activate.php?x=" . mysql_insert_id() . "&y=$a";
  9. mail($_POST['email'], 'Registration Confirmation', $body, 'From: admin@sitename.com');

  10. // Show thank you message
  11. echo '

    Thank You!

  12. You have been registered, you have been sent an e-mail to the address you specified before. Please check your e-mails to activate your account.';
  13. } else {
  14. echo 'You could not be registered, please contact us about the problem and we will fix it as soon as we can.';
  15. }

This is the part where we do our error checking, if our $errors variable is empty (no errors) then we continue on with the form. So we insert everything into our users table, run the query, then check if it worked using mysql_affected_rows() == 1. If our query only affected 1 row (only inserted 1 user, no more and no less.) then our query worked, you are shown a message and the e-mail is sent to the user.

**UPDATE V1.2** - The query has been fixed, and everything has been personally tested and works now. If there is still more bugs please tell me.

If it didn't work, (the query didn't work) you are shown an error message.

PHP:
  1. } else {
  2. echo '

    Error!

  3. The following error(s) occured:
    '
    ;

  4. foreach ($errors as $msg) {
  5. echo " - \"red\">$msg
    \n";
  6. }
  7. }
  8. }
  9. ?>

This is the finishing of the PHP section of our registration script, this is always where we check for errors. If the $errors array was not empty then the user is shown an error message and we use a foreach loop to display all of our errors and echo them out to the user. Then we end our PHP section.

HTML:
  1. text" name="username" value="<?php if (isset($_POST['username'])) echo $_POST['username']; ?>" size="30" maxlength="30" /> Username


  2. type="password" name="password1" size="30" maxlength="40" /> Password


  3. type="password" name="password2" size="30" maxlength="40" /> Confirm Password


  4. type="text" name="email" size="30" maxlength="30" value="" /> Email Address


  5. submit" name="submit" value="Register" />

  6. hidden" name="submitted" value="TRUE" />

So I lied, there is still a little tiny bit of PHP but very simple stuff. Here we just create our form, with the corresponding names as in our PHP script. Make sure you name your the hidden input as submitted, this is how our PHP script knows that the form is submitted.

That is it for our registration part of our script, now we just have to do the activation part, this is a simple little script.

PHP:

  1. if (isset($_GET['x'])) {
  2. $x = (int) $_GET['x'];
  3. } else {
  4. $x = 0;
  5. }
  6. if (isset($_GET['y'])) {
  7. $y = $_GET['y'];
  8. } else {
  9. $y = 0;
  10. }

  11. if ( ($x> 0) && (strlen($y) == 32)) {

  12. require_once ('mysql_connect.php');
  13. $query = "UPDATE users SET active=NULL WHERE (user_id=$x AND active='" . $y . "') LIMIT 1";
  14. $result = mysql_query($query);

  15. if (mysql_affected_rows() == 1) {
  16. echo "

    Your account is now active. You may now log in.

    "
    ;
  17. } else {
  18. echo '

    Your account could not be activated. Please re-check the link or contact the system administrator.

    '
    ;
  19. }


  20. } else {

  21. echo 'Activation link not valid!';

  22. }
  23. ?>

This is just a simple little script, we start off by checking the x and y values in the URL to check if they are valid (or if someone is messing with us), we inclue our mysql_connect.php file into our script, since we will be using the database to query the right user. A user is considered active when the active field for there name is NULL (empty), so if the x and y values are right and everything works, we then set the active field to NULL. If only 1 account was affected, we echo out a success message and everything is done! If not, then the appropriate error message is echoed and the script stops.

Source - http://www.example.com/php/registration-script/

2 comments:

Anonymous said...

PECS is Microsoft & ISO 9001 certified company that provide new media
solutions all across the globe having sales office in UK and India. We
provide solutions related Web Design & Development, SEO and Bespoke
Software for all business domains.

Akash said...

How lucky your are,who working with PECS. what certified by Microsoft. well, i am not a member of big company but i am very happy to be part of web development company.