FRIHOSTFORUMSSEARCHFAQTOSBLOGSCOMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Login System Tutorial Part 1 Creating Registration





rfwrangler
I have seen a lot of people on here asking for how to do a system for members and allowing a login function for these members. I thought that I would address this and write a tutorial for people on here to use in setting up their own login system. Hopefully the moderators will make this post sticky and it will be easy for people to find and use.

The ways to make a log in system for protect and restrict access to a site are numerous and each person has their own preferences for how they want to accomplish this. The tutorial that I am writing here is meant as a guide and to teach you how to create your own user(membership) system. Remember that this is one way to do this and I am sure that there are ways that others think are better. I do invite the users to this site to add to this tutorial and to improve on it and I invite questions from people that do not understand what I am saying through out the tutorial.

I will break this tutorial in to a series of tutorials based on natural break points. This is the first in the series and is about creating a script to register users.

With that being said and with out further ado let’s get to coding!

The first thing that is needed is a way for your users to sign up for membership. This is fairly straight forward and involves setting up a form that will be processed and the data from that form will be entered into a MySQL database.

STEP 1: (Set up the database)

So let’s start with setting up the database on your MySQL server. There are several way that you can do this the easiest is probably to use phpmyadmin and set the table up using that.

The way that I often set up my database tables are to write them in a text editor such as Crimson Editor http://www.crimsoneditor.com/. I then write the SQL to set up the table and save it as a .sql file. This way I have the file if I need it in the future.

The membership table that we will set up will have a unique id for each user as well as unique usernames and we will check that the users email address is only in the table once as well. This will give each user unique characteristics that we are able to use for identification.

Code:
CREATE TABLE members(
   id int NOT NULL auto_increment,
   first_name varchar(25) NOT NULL default ‘‘,
   last_name varchar(25) NOT NULL default ‘’,
   email varchar(50) NOT NULL default ’’,
   username varchar(25) NOT NULL default ’’,
   password varchar(25) NOT NULL default ‘’,
        activated enum NOT NULL default '0',
   date timestamp() NOT NULL default ‘0000-00-00 00:00:00’,
   UNIQUE KEY id (id),
   PRIMARY KEY id (id),
   UNIQUE KEY email (email),
   UNIQUE KEY username (username)
);



This sets up a MySQL table, named members, in your database with the primary key of ‘id’. This is set as an auto_incrementing field that will automatically assign a unique value for each row in the table. This is the primary identifier of the record set in the table. The other unique fields are to insure that usernames and email addresses are not duplicated in the database. Having these as unique fields allows us to set up a password recovery feature and allows users to be uniquely identified when they log in to the site. You can always add more fields to the table depending on your needs.

STEP 2: (Set up user registration)

The set up for the user registration involves a form to collect the user’s information and to be sent to the database after error checking and sterilizing the user input. We will go through the script step by step and I will show the entire code at the end.

First we need a form for the user to enter their information the code for this is as follows:

Code:
<form name=”registration_form” action = “$_PHPSELF” method = “post” id=”registration_form”>



Here we have set up a form that will use the action of $_PHPSELF with a post method. I have done this so that our registration form will have all of the scripting that we need included in the same page. The $_PHPSELF just means that the form will call the same page that it is located on. The POST method that we are using is so that the information is sent via the headers instead of being sent in the URL. The POST method is more secure than GET and since we are sending a password it is better to send this in the headers.

Code:
<label for=”first_name”>*FIRST NAME:</label><br />
   <input name=”first_name” type=”text” id=”first_name” size=”25” maxsize=”25”/><br />
   <label for=”last_name”>*LAST NAME:</label><br />
   <input name=”last_name” type=”text” id=”last_name” size=”25” maxsize=”25” /><br />
   <label for=”email”>*EMAIL ADDRESS:</label><br />
   <input name=”email” type=”text” id=”email” size=”45” maxsize=”100” /><br />
   <label for=”username”>*USERNAME:</label><br />
   <input name=”username” type=”text” id=”username” size=”25” maxsize=”25” /><br />
   <label for=”password”>*PASSWORD:</label><br />
   <input name=”password” type=”password” id=”password” size=”25” maxsize=”25” /><br />
   <input name=”register” type=”submit” id=”register” value=”REGISTER” />
</form>


We will use this code in an echo statement in our script.

This is just standard HTML for the fields on the form that we are using to get the information. Since this is the first time that the form is being displayed all of the values will be empty. I have set the field size and the maximum value size on each of the fields. This is so that the user doesn’t try to send a value that is larger than the table can handle for the respective field in our database.

Now we need to start the script to process the information that we get from the user. When we process our information a few things need to be kept in mind about using forms. Number one: NEVER, expect your users to submit the information the way that you want it submitted. Two: there will always be someone that will try to exploit your forms. And three: someone will always try to submit your form with nothing in the fields.

So let’s start setting up our file to process the information

Code:
<?php
   //check if the form was submitted or if this page was loaded
   if($_POST[‘submit’] == ‘register’){
   //get the variables from the submitted form
      $first_name = stripslashes($_POST[‘first_name’]);
      $last_name = stripslashes($_POST[‘last_name’]);
      $email = stripslashes($_POST[‘email’]);
      $username = stripslashes($_POST[‘username’]);
      $password = stripslashes($_POST[‘password’]);


Here we check if the form was submitted and if that was the reason for this page call. If this page call was due to the form being submitted then we take the POST variables and assign them to simple variables that are easier to remember. We use the stripslashes() function to remove any unwanted slashes from the user input.

The next thing that we want to do is check to see if the required fields have a value in them.

Code:
if(($first_name == ‘’) || ($last_name == ‘’) || ($email == ‘’) || ($username == ‘’) || ($password == ‘’) || (!isset($first_name)) || (!isset($last_name)) || (!isset($email)) || (!isset($username)) || (!isset($password))){
echo ‘You forgot the following required fields:<br />
<ul>’;
if(($first_name == ‘’) || (!isset($first_name))){
echo ‘<li>FIRST NAME</li>’;
}
if(($last_name == ‘’) || (!isset($last_name))){
echo ‘<li>LAST NAME</li>’;
}
if(($email == ‘’) || (!isset($email))){
echo ‘<li>EMAIL ADDRESS</li>’;
}
if(($username == ‘’) || (!isset($username))){
echo ‘<li>USERNAME</li>’;
}
if(($password == ‘’) || (!isset($password))){
echo ‘<li>PASSWORD</li>’;
}
echo ‘</ul><br />
Please fill in these values and submit the form again.<br />’;
//Display the form again
echo ‘<form name=”registration_form” action = “$_PHPSELF” method = “post” id=”registration_form”>

<label for=”first_name”>*FIRST NAME:</label><br />

<input name=”first_name” type=”text” id=”first_name” size=”25” maxsize=”25” value = “’ . $first_name . ‘” /><br />

<label for=”last_name”>*LAST NAME:</label><br />

<input name=”last_name” type=”text” id=”last_name” size=”25” maxsize=”25” value=”’ . $last_name . ‘” /><br />

<label for=”email”>*EMAIL ADDRESS:</label><br />

<input name=”email” type=”text” id=”email” size=”45” maxsize=”100” value=”’ . $email . ‘” /><br />

<label for=”username”>*USERNAME:</label><br />

<input name=”username” type=”text” id=”username” size=”25” maxsize=”25” value=”’ . $username . ‘” /><br />

<label for=”password”>*PASSWORD:</label><br />
<input name=”password” type=”password” id=”password” size=”25” maxsize=”25” value=”’ . $password . ‘” /><br />

<input name=”register” type=”submit” id=”register” value=”REGISTER” />
</form>’;



In the above code we check that the user has filled in all of the required fields. If a field(s) is missing we alert the user and display the form again with the values that were submitted already filled out in the form. This keeps the user from have to refill these fields making your form more user friendly.

The next thing that we want to do is check if the email address is a valid email address. This is a function that I found on PHPFreaks.com for doing this.


Code:
function is_valid_email($address) {
return (eregi(
'^[-!#$%&\'*+\./0-9=?A-Z^_`{|}~]+'.      // the user name
'@'.                                     // the ubiquitous at-sign
'([-0-9A-Z]+.)+' .               // host, sub-, and domain names
'([0-9A-Z]){2,4}$',            // top-level domain (TLD)
trim($address)));
}
$f_email = strtolower(trim($email));
if (is_valid_email($f_email)) {


This function takes the submitted email address and checks for various characteristics that are typical of all email addresses. The first item it checks is that there is a string before the @ sign. Then it checks that there is one and only one @ symbol that there is a string of characters leading to a . then a string of 2-4 characters for the top level domain name. If any of these return false then the email is not valid and the function will not return.

If the email returns as valid then we need to check the database to see if our unique identifiers are in the database. This is the username and the email address.


Code:
$user = ‘[i]your database username[/i]’;
$pass = ‘[i]your database password[/i]’;
$host = ‘localhost’;
$dbname = ‘[i]your database name[/i]’;



These are the database variables that you will need to make a connection to the database that you are using to hold your site members. We will now make a connection to the database so that we can check the username and email address against the existing entries.


Code:
$dbconn = mysql_connect($host, $user, $pass) or die(‘Could not connect to database server’);
$db = mysql_select_database($dbname, $dbconn) or die(‘Could not select database’);


Now that we have connected to our database we need to run a query to check if the username or email address exist.


Code:
if($db){
$username_query = “SELECT username FROM members WHERE username = $username”;

$email_query = “SELECT email FROM members WHERE email = $email”;

$user_check = mysql_query($username_query);

$email_check = mysql_query($email_query);

$user_rows = mysql_num_rows($user_check);

$email_rows = mysql_num_rows($email_check);

if(($user_rows >=1) || ($email_rows >=1)){
echo ‘<p>You have made a duplicate entry.<br />’;
if($user_rows >=1){
echo “The USERNAME: $username is already in our database.<br />”;
unset($username);
}
if($email_rows>=1){
echo “The EMAIL ADDRESS: $email is already in our database.”;
unset($email);
}
echo “Please make these corrections and submit the form again.</p>”;
//Display the form again.
echo “‘<form name=”registration_form” action = “$_PHPSELF” method = “post” id=”registration_form”>

<label for=”first_name”>*FIRST NAME:</label><br />

<input name=”first_name” type=”text” id=”first_name” size=”25” maxsize=”25” value = “’ . $first_name . ‘” />
<br />

<label for=”last_name”>*LAST NAME:</label><br />

<input name=”last_name” type=”text” id=”last_name” size=”25” maxsize=”25” value=”’ . $last_name . ‘” />
<br />

<label for=”email”>*EMAIL ADDRESS:</label><br />

<input name=”email” type=”text” id=”email” size=”45” maxsize=”100” value=”’ . $email . ‘” /><br />

<label for=”username”>*USERNAME:</label><br />

<input name=”username” type=”text” id=”username” size=”25” maxsize=”25” value=”’ . $username . ‘” /><br />

<label for=”password”>*PASSWORD:</label><br />
<input name=”password” type=”password” id=”password” size=”25” maxsize=”25” value=”’ . $password . ‘” /><br />

<input name=”register” type=”submit” id=”register” value=”REGISTER” />
</form>’;


Here we check the username and email address against the database and if they exist we alert the user and unset the variable holding the value. We then display the form again for the user to make any corrections that are needed. If everything checks out we are ready for the next phase of the registration script. Stay with me we only have a couple more steps to our registration form.

We need to enter the values that we have collected from the user that is registering with our site into our database so that they are able to come back to our site and not have to reregister. We will use these values that we enter into the database to verify that they are an authorized user and allow them access to the restricted member’s area.


Code:
} else {
$dbpass = md5($password);
$sql = “INSERT INTO members (first_name, last_name, email, username, password)
VALUES ($first_name, $last_name, $email, $username, $dbpass)”;
mysql_query($sql);
            mysql_close();


The first thing that we do is use the md5 hash to encrypt our password so that the actual password is not stored in our database. This offers a little more security so that if some how someone gains that password value that is in the database it is not usable for access to the restricted pages. We then insert the values that our user has submitted into our database through the mysql_query() function. The way that we set up oour database in the beginning will automatically set the id to a unique id and the date will be set with a timestamp entered by MySQL.

Now we will send an email to our user so that they have a record of their username and password to our site. We will also set a link for our user to use to activate their account before we allow access to the site. This is another check to insure that the email address that they have submitted is an actual email address.


Code:
$to = $email
$from = ‘[i]your website and the webmaster’s email address[/i] nX-Mailer: PHP/’ . phpversion();
$subject = “Your account information at [i]your website[/i]”;
$message = “You recently registered with [i]your website[/i].  Here is your log in information:

Username: $username
Password: $password
Once you activate your account through the link below you will be able to login to your account.

Click the link to activate:
http://www.[i]yourwebsite[/i].net/activate.php?id=$user_id&code=$db_password

Thank you
The Webmaster

This is an automated response PLEASE DO NOT REPLY”;
mail($to, $subject, $message, $from);


This will send the user an email that they will be able to activate their account with and it has their username and password. This is sent using the PHP mail() function.

The last thing that we need to do is display to the user that the registration is complete and that we sent them an email to activate their account.


Code:
echo “<p>Registration completed. Please check your email to activate your account.<br />
You will not be able to login to your account until it has been activated.</p>”;
         }



If this is the first load for the page (i.e. the form has not been submitted) Then we will show the form that we wrote in the beginning of the tutorial.


Code:
} else {
//display the form for registration
echo ‘<form name=”registration_form” action = “$_PHPSELF” method = “post” id=”registration_form”>

<label for=”first_name”>*FIRST NAME:</label><br />

<input name=”first_name” type=”text” id=”first_name” size=”25” maxsize=”25”/><br />

<label for=”last_name”>*LAST NAME:</label><br />

<input name=”last_name” type=”text” id=”last_name” size=”25” maxsize=”25” /><br />

<label for=”email”>*EMAIL ADDRESS:</label><br />

<input name=”email” type=”text” id=”email” size=”45” maxsize=”100” /><br />

<label for=”username”>*USERNAME:</label><br />

<input name=”username” type=”text” id=”username” size=”25” maxsize=”25” /><br />

<label for=”password”>*PASSWORD:</label><br />

<input name=”password” type=”password” id=”password” size=”25” maxsize=”25” /><br />

<input name=”register” type=”submit” id=”register” value=”REGISTER” />
</form>’;
}
?>



This is the first in this series of tutorials about building a membership system for your website. In the next tutorial I will show you how to write the script for the activation of the user account and the login script for the site. This will get you started towards having a login system for your website using PHP and MySQL.

Database SQL code for MySQL:

Code:
CREATE TABLE members(
   id int NOT NULL auto_increment,
   first_name varchar(25) NOT NULL default ‘‘,
   last_name varchar(25) NOT NULL default ‘’,
   email varchar(50) NOT NULL default ’’,
   username varchar(25) NOT NULL default ’’,
   password varchar(25) NOT NULL default ‘’,
   date timestamp() NOT NULL default ‘0000-00-00 00:00:00’,
   UNIQUE KEY id (id),
   PRIMARY KEY id (id),
   UNIQUE KEY email (email),
   UNIQUE KEY username (username)
);


The registration script register.php
Code:
<?php
   //check if the form was submitted or if this page was loaded
   if($_POST[‘submit’] == ‘register’){
   //get the variables from the submitted form
      $first_name = stripslashes($_POST[‘first_name’]);
      $last_name = stripslashes($_POST[‘last_name’]);
      $email = stripslashes($_POST[‘email’]);
      $username = stripslashes($_POST[‘username’]);
      $password = stripslashes($_POST[‘password’]);
if(($first_name == ‘’) || ($last_name == ‘’) || ($email == ‘’) || ($username == ‘’) || ($password == ‘’) || (!isset($first_name)) || (!isset($last_name)) || (!isset($email)) || (!isset($username)) || (!isset($password))){
echo ‘You forgot the following required fields:<br />
<ul>’;
if(($first_name == ‘’) || (!isset($first_name))){
echo ‘<li>FIRST NAME</li>’;
}
if(($last_name == ‘’) || (!isset($last_name))){
echo ‘<li>LAST NAME</li>’;
}
if(($email == ‘’) || (!isset($email))){
echo ‘<li>EMAIL ADDRESS</li>’;
}
if(($username == ‘’) || (!isset($username))){
echo ‘<li>USERNAME</li>’;
}
if(($password == ‘’) || (!isset($password))){
echo ‘<li>PASSWORD</li>’;
}
echo ‘</ul><br />
Please fill in these values and submit the form again.<br />’;
//Display the form again
echo ‘<form name=”registration_form” action = “$_PHPSELF” method = “post” id=”registration_form”>

<label for=”first_name”>*FIRST NAME:</label><br />

<input name=”first_name” type=”text” id=”first_name” size=”25” maxsize=”25” value = “’ . $first_name . ‘” /><br />

<label for=”last_name”>*LAST NAME:</label><br />

<input name=”last_name” type=”text” id=”last_name” size=”25” maxsize=”25” value=”’ . $last_name . ‘” /><br />

<label for=”email”>*EMAIL ADDRESS:</label><br />

<input name=”email” type=”text” id=”email” size=”45” maxsize=”100” value=”’ . $email . ‘” /><br />

<label for=”username”>*USERNAME:</label><br />

<input name=”username” type=”text” id=”username” size=”25” maxsize=”25” value=”’ . $username . ‘” /><br />

<label for=”password”>*PASSWORD:</label><br />
<input name=”password” type=”password” id=”password” size=”25” maxsize=”25” value=”’ . $password . ‘” /><br />

<input name=”register” type=”submit” id=”register” value=”REGISTER” />
</form>’;
function is_valid_email($address) {
return (eregi(
'^[-!#$%&\'*+\./0-9=?A-Z^_`{|}~]+'.      // the user name
'@'.                                     // the ubiquitous at-sign
'([-0-9A-Z]+.)+' .               // host, sub-, and domain names
'([0-9A-Z]){2,4}$',            // top-level domain (TLD)
trim($address)));
}
$f_email = strtolower(trim($email));
if (is_valid_email($f_email)) {
$user = ‘[i]your database username[/i]’;
$pass = ‘[i]your database password[/i]’;
$host = ‘localhost’;
$dbname = ‘[i]your database name[/i]’;

$dbconn = mysql_connect($host, $user, $pass) or die(‘Could not connect to database server’);
$db = mysql_select_database($dbname, $dbconn) or die(‘Could not select database’);
if($db){
$username_query = “SELECT username FROM members WHERE username = $username”;

$email_query = “SELECT email FROM members WHERE email = $email”;

$user_check = mysql_query($username_query);

$email_check = mysql_query($email_query);

$user_rows = mysql_num_rows($user_check);

$email_rows = mysql_num_rows($email_check);

if(($user_rows >=1) || ($email_rows >=1)){
echo ‘<p>You have made a duplicate entry.<br />’;
if($user_rows >=1){
echo “The USERNAME: $username is already in our database.<br />”;
unset($username);
}
if($email_rows>=1){
echo “The EMAIL ADDRESS: $email is already in our database.”;
unset($email);
}
echo “Please make these corrections and submit the form again.</p>”;
//Display the form again.
echo “‘<form name=”registration_form” action = “$_PHPSELF” method = “post” id=”registration_form”>

<label for=”first_name”>*FIRST NAME:</label><br />

<input name=”first_name” type=”text” id=”first_name” size=”25” maxsize=”25” value = “’ . $first_name . ‘” />
<br />

<label for=”last_name”>*LAST NAME:</label><br />

<input name=”last_name” type=”text” id=”last_name” size=”25” maxsize=”25” value=”’ . $last_name . ‘” />
<br />

<label for=”email”>*EMAIL ADDRESS:</label><br />

<input name=”email” type=”text” id=”email” size=”45” maxsize=”100” value=”’ . $email . ‘” /><br />

<label for=”username”>*USERNAME:</label><br />

<input name=”username” type=”text” id=”username” size=”25” maxsize=”25” value=”’ . $username . ‘” /><br />

<label for=”password”>*PASSWORD:</label><br />
<input name=”password” type=”password” id=”password” size=”25” maxsize=”25” value=”’ . $password . ‘” /><br />

<input name=”register” type=”submit” id=”register” value=”REGISTER” />
</form>’;
      } else {
$dbpass = md5($password);
$sql = “INSERT INTO members (first_name, last_name, email, username, password)
VALUES ($first_name, $last_name, $email, $username, $dbpass)”;
mysql_query($sql);
            mysql_close();
$to = $email
$from = ‘[i]your website and the webmaster’s email address[/i] nX-Mailer: PHP/’ . phpversion();
$subject = “Your account information at [i]your website[/i]”;
$message = “You recently registered with [i]your website[/i].  Here is your log in information:

Username: $username
Password: $password
Once you activate your account through the link below you will be able to login to your account.

Click the link to activate:
http://www.[i]yourwebsite[/i].net/activate.php?id=$user_id&code=$db_password

Thank you
The Webmaster

This is an automated response PLEASE DO NOT REPLY”;
mail($to, $subject, $message, $from);
echo “<p>Registration completed. Please check your email to activate your account.<br />
You will not be able to login to your account until it has been activated.</p>”;
         }
} else {
//display the form for registration
echo ‘<form name=”registration_form” action = “$_PHPSELF” method = “post” id=”registration_form”>

<label for=”first_name”>*FIRST NAME:</label><br />

<input name=”first_name” type=”text” id=”first_name” size=”25” maxsize=”25”/><br />

<label for=”last_name”>*LAST NAME:</label><br />

<input name=”last_name” type=”text” id=”last_name” size=”25” maxsize=”25” /><br />

<label for=”email”>*EMAIL ADDRESS:</label><br />

<input name=”email” type=”text” id=”email” size=”45” maxsize=”100” /><br />

<label for=”username”>*USERNAME:</label><br />

<input name=”username” type=”text” id=”username” size=”25” maxsize=”25” /><br />

<label for=”password”>*PASSWORD:</label><br />

<input name=”password” type=”password” id=”password” size=”25” maxsize=”25” /><br />

<input name=”register” type=”submit” id=”register” value=”REGISTER” />
</form>’;
}
?>
hexkid
Here are a few points about your script:

    It relies on register globals being on ($_PHPSELF).
    The md5() returns a string 32 characters long. The database is set up for 25 characters.
    You use some very strange characters for quotes!
    Why is the form repeated 3 times in the script. Write a function!
    You don't need to stripslashes() (in fact, you shouldn't) when the server is configured with magic_gpc off.
    The variables you use for MySQL are not sanitized!!!!!!
    The indentation, IMO, sucks.


Anyway, thank you for the code.
Rhysige
functions are your friend ^_^
rfwrangler
Yes I know that I could have used functions in a lot of this script the idea behind this was to give new scripters a place to start. I worked to keep this script simple and easy to understand. Thank you for your input on this though and in future segments I will use functions. I do welcome the input from other PHPers.

In the beginning of this article I stated that there are many different ways to write a memebership system. I choose to do it this way to keep things easy for beginning programmers and give them a platform to build from.

While this is not the best way to build a membership system it is a way that will teach basics such as syntax and flow. This tutorial will be built on in later installments and this very script will be revisited with better ways to build this. Ideally I should use a class to test the states of the page and from that class determine the course of action. This will be a later tutorial.

Again thank you for the input it is very welcome.
hexkid
rfwrangler wrote:
In the beginning of this article I stated that there are many different ways to write a memebership system. I choose to do it this way to keep things easy for beginning programmers and give them a platform to build from.
If a beginner selects your code, copies it, and pastes into a new file, that new file will not be a working PHP script. That's the worst thing to do to a beginner Wink

I appreciate the time and effort you've taken to write and comment your code, the reason for my post above was to point areas you could try to work on and make it even easier for beginners.
rfwrangler
I do thank you for your input and your advice I will look at what I have wrote and see about re formatting it to better accomidate a beginner. Thank you for the advice and the input that is what this is about.
Diablosblizz
Great script, but like hexkid said it is not friendly with beginners, what I recommend, is include what each little bit of php in each page does. But, I think that would be to long for the forums, so "try" to make a page on a frihost server.

But, overall its a good script.
Bejeweledhorses
Shocked
whiskers27
Nice tutorial thanks now i can have people sign up on my sites awsome
Related topics
html login system
PHP Tutorial: Basic Shoutbox w/ MySQL
Simple login system
Login System help
AJAX tutorial [2nd part now updated]
Developing a Login System with PHP and MySQL
i need a single user login system
Frih$ on offer for PHP Login System
I need help with a login system tutorial???
Could someone create a really simple login system???
login and register system error
Login for pages and forum etc...
Login system with uploading features!
Creating safe persistent login system
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.