Creating a registration form using PHP

in PHP Form Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password. The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code
You can download the whole source code for the registration/login system from the link below: Configuration & Upload The ReadMe file contains detailed instructions. Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website's name, your email address etc). Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

We need to check if name and email. Here is the registration form: <form id='register' action='register.php' method='post' accept-charset='UTF-8'> <fieldset > <legend>Register</legend> <input type='hidden' name='submitted' id='submitted' value='1'/> <label for='name' >Your Full Name*: </label> <input type='text' name='name' id='name' maxlength="50" /> <label for='email' >Email Address*:</label> <input type='text' name='email' id='email' maxlength="50" /> <label for='username' >UserName*:</label> <input type='text' name='username' id='username' maxlength="50" /> <label for='password' >Password*:</label> <input type='password' name='password' id='password' maxlength="50" /> <input type='submit' name='Submit' value='Submit' /> </fieldset> </form> So.In order to create a user account. we have text fields for name. Note that we are using the password widget for better usability. So let's limit ourselves to just those fields. . Of course. his email address and his desired username and password. so we make sure that we have all the data required to create the user account. We need his name. but a long form is always a turn-off. we need to gather a minimal amount of information from the user. email and the password. and password are filled in and that the email is in the proper format. Form validation At this point it is a good idea to put some form validation code in place. we can ask for more information at this point.

frmvalidator."Please provide a valid email address"). with lesser code. if(!$this->ValidateRegistrationSubmission()) { return false. we will use the PHP form validation script Handling the form submission Now we have to handle the form data that is submitted."req"."email". saving to database etc). Here is the sequence (see the file fg_membersite. } First. if(!$this->SaveToDatabase($formvars)) { return false. Here is a sample JavaScript validation code to be used for the sample form we created earlier: var frmvalidator = new Validator("register"). } $this->SendAdminIntimationEmail($formvars). frmvalidator.addValidation("email"."req".addValidation("password"."req". Then we collect and 'sanitize' the form submission data (always do this before sending email.php in the downloaded source): function RegisterUser() { if(!isset($_POST['submitted'])) { return false. we validate the form submission.We can use the free JavaScript form validation script to add form validations quickly and easily. } $formvars = array().EnableOnPageErrorDisplay(). frmvalidator. return true.addValidation("username".EnableMsgsTogether(). frmvalidator."Please provide a username"). The form submission is then saved . we will also have the same validations on the server side too. frmvalidator.addValidation("email"."Please provide your name")."Please provide a password"). To be on the safe side."Please provide your email address"). } if(!$this->SendUserConfirmationEmail($formvars)) { return false. For server side validations. frmvalidator."req". } $this->CollectRegistrationSubmission($formvars).addValidation("name". frmvalidator.

return false. we return error back to the user. } if(!$this->IsFieldUnique($formvars. } Note that you have configured the Database login details in the membersite_config. Then we make sure that the username and email are unique. The database table structure This is the table structure. After logging in. function SaveToDatabase(&$formvars) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!").php file.php file creates the table. you can use "localhost" for database host. If it is not unique. We send an email to the user requesting confirmation. Most of the cases. return false.(If not.'username')) { $this->HandleError("This UserName is already used. return false. } if(!$this->InsertIntoDB($formvars)) { $this->HandleError("Inserting to Database failed!"). } if(!$this->IsFieldUnique($formvars. } if(!$this->Ensuretable()) { return false. Here is the code: function CreateTable() . The CreateTable() function in the fg_membersite. Please try another username").to the database table. Saving the data in the database Now that we gathered all the data. } return true.'email')) { $this->HandleError("This email is already registered"). we make sure that the table is existing. return false. the script will create the required table). Here is how we save the form submission to the database. we need to store it into the database. Then we intimate the admin that a user has registered.

{ $qry = "Create Table $this->tablename (". "password VARCHAR( 32 ) NOT NULL .$this->connection)) { $this->HandleDBError("Error creating the table \nquery was\n $qry"). "PRIMARY KEY ( id_user )". "username VARCHAR( 16 ) NOT NULL . email. '". and is also the primary key of the table. username. $this->SanitizeForSQL($formvars['name']) . "' . $this->SanitizeForSQL($formvars['username']) . } The id_user field will contain the unique id of the user.".". } . '". We do this because. if(!mysql_query($qry. Notice that we allow 32 characters for the password field. "email VARCHAR( 64 ) NOT NULL . "phone_number VARCHAR( 16 ) NOT NULL . } return true. '".". "name VARCHAR( 128 ) NOT NULL . as an added security measure. password. Inserting the registration to the table Here is the code that we use to insert data into the database. we will store the password in the database encrypted using MD5. function InsertIntoDB(&$formvars) { $confirmcode = $this->MakeConfirmationMd5($formvars['email']). '".". "confirmcode VARCHAR(32) . if(!mysql_query( $insert_query . "' .". return false.". "' . md5($formvars['password']) .$this->connection)) { $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"). $this->SanitizeForSQL($formvars['email']) . $insert_query = 'insert into '. ")". $confirmcode .'( name. we won't be able to recover the password in case the user forgets it. We will have all our data available in the $formvars array. "' . return false.$this->tablename. '" )'. "id_user INT NOT NULL AUTO_INCREMENT .". Please note that because MD5 is an one-way encryption method. confirmcode ) values ( "' .

In the confirmreg."\r\n\r\n". Sending emails Now that we have the registration in our database. $confirm_url = $this>GetAbsoluteURLFolder().php?code=XXXX (where XXXX is the confirmation code). } We use the free PHPMailer script to send the email.$formvars['name']. After completing all these operations successfully. "Thanks for your registration with ".$formvars['name']).php?code='. we send an email to the admin (configured in the membersite_config. "Please click the link below to confirm your registration. if(!$mailer->Send()) { $this->HandleError("Failed sending registration confirmation email. Also. } Notice that we use PHP function md5() to encrypt the password before inserting it into the database. Note that we make the confirmation URL point to confirmreg.'/confirmreg. The user has to click a link in the confirmation email to complete the registration process."\r\n". $this->sitename. we search for this confirmation code and update the 'confirmed' field in the table. "\r\n". "Regards. we make the unique confirmation code from the user's email address. function SendUserConfirmationEmail(&$formvars) { $mailer = new PHPMailer().php script. $mailer->From = $this->GetFromAddress().$this->sitename.php file) . $mailer->Body ="Hello ".\r\n".return true. we will send a confirmation email to the user. "$confirm_url\r\n".\r\n". $mailer->CharSet = 'utf-8'. return false. } return true. $mailer->AddAddress($formvars['email']. $confirmcode = urlencode($this->MakeConfirmationMd5($formvars['email'])).$confirmcode. $mailer->Subject = "Your registration with ".").$this->sitename. "Webmaster\r\n".