Monday, June 18, 2012

MySQL & PHP: user accounts - Part 2

The PHP Sign Up Process

In signup.php the first PHP code we will write is the code to start the session, then we can start saving information. The PHP code to start a session is "session_start();". In this guide I added it to the header.php file and included it in signup.php. The include() function allows you to include a file with other code into your current PHP file. This makes it easier for you, cause it stops you from having to keep writing the same HTML or PHP code over and over again. The code to include a file is include("file.php");".

signup.php

<? include("header.php"); ?>

<head>
<title>First login PHP Script</title>
<link rel="stylesheet" type="text/css" href="css/index.css" />
</head>

<BODY>

<div id="content">

 <div id="header">

 </div>
    
 <div id="nav">
 
 </div>
 
 <div id="right">
   <form action="signup_process.php" method="post" >
    <span class="fname"> 
      <label for="firstname">First Name:</label><input name="fname" type="text"/><br />
     </span>
    <span class="lname"> 
      <label for="lastname">Last Name:</label><input name="lname"  type="text" /><br />
    </span>
    <span class="mail">
      <label for="emailaddress">Email:</label><input name="email" type="text"  /><br />
    </span>
    <span class="uname"> 
      <label for="username">Username:</label><input name="username"  type="text"/><br />
     </span>
     <span class="pass1"> 
      <label for="password1">Password:</label><input name="password1"  type="password" /><br />
     </span>
     <span class="pass2"> 
      <label for="password2">Password (retype):</label><input name="password2"  type="password" /><br />
     </span>
     <input type="submit" value="Sign Up" name="submit" class="submit" />

   </form>

 </div>


</div>

<? include("footer.php"); ?>

signup_process.php

The signup_process.php file is identical to the signup.php file, except the PHP code will be written in it. The first step is to connect to the database so the user can sign up, so we will include the config.php we created from part 1. To include it we will use the PHP require_once() function, it will check to see if the file has already been included, and if so, not include it again.

//Include database connection file
 require_once('config.php');

Next we will be grabbing the user information the user typed into the form. This is when it is important to remember the names of each input type and the method used to grab the data from the form. We use an if construct to check to see if the signup button has been clicked. To tell PHP to check this, we use isset. The isset checks to see whether the input name, submit, from the form has been created or set, if it has it returns true. Since we used the POST method we use $_POST['input_name'] to tell PHP which POST we are checking or using in the form. In this guide it is the signup button named sumbit, so it is $_POST['sumbit'].

if(isset($_POST['submit']))  {

//PHP Code

}

Next we are going to create a different variable for each input the user entered into the form. The PHP code to create this is "$variable = mysql_real_escape_string($_POST['input_name']);". We use mysql_real_escape_string for SQL injection prevention, which is another topic all together. What mysql_real_escape_string does though is remove the quotes in a string and replace them with escaped quotes for use in SQL.

//create the input variables and prevent SQL injection
   $username = mysql_real_escape_string($_POST['username']);
   $password1 = mysql_real_escape_string($_POST['password1']);
   $password2 = mysql_real_escape_string($_POST['password2']);
   $email = mysql_real_escape_string($_POST['email']);
   $fname = mysql_real_escape_string($_POST['fname']);
   $lname = mysql_real_escape_string($_POST['lname']);

The next step is to make sure that the username and password fields are not empty and the passwords variables are equal. We start a second if construct and use the empty() PHP function, which checks to see if the the variable is empty or not. In PHP !empty means not empty, so we use "if(!empty($username) && !empty($password1) && !empty($password2) && ($password1 == $password2))".

//check to make sure that the username and password fields are not empty and that the passwords match
if(!empty($username) && !empty($password1) && !empty($password2) &&   ($password1 == $password2)) {

     
     }     
     elseif ($password1 != $password2)    {

     //PHP Code
     }

     else   {

     //PHP Code
     }

The next step is to make sure the username does not already exist in the table. To do this we create a variable called query for the MySQL query, The code is "$query = "SELECT * FROM tuser WHERE username = '$username';". The Query selects all columns from table tuser, * means all columns, where the username equals the username entered, notice how the username variable was used again for the username. We get the information from the executed MySQL query and create a variable called data that contains the data. The MySQL query is executed using mysql_query($query). The code is "$data = mysql_query($query);". We use a third if construct, the data variable, and the mysql_num_rows() function to make sure that no usernames exist in the table. The code to check for no username looks like this, "if(mysql_num_rows($data) == 0)". If there is no row created with the username from the data then the users data is inserted into the table.

//make sure the username does not already exist, create sql query to check username
$query = "SELECT * FROM tuser WHERE username = '$username' "; 
       
//the data variable connects to the database and executes the MySQL query
$data = mysql_query($query);

//check to make sure no username row exists in the data, if data is empty or zero
if(mysql_num_rows($data) == 0)    {
       
     //PHP Code
     }
     else {
     
     //PHP Code
     }

The next step is to create the MySQL query to insert the user's data into the table, the query variable is created for the query, the code is, $query = "INSERT INTO tuser (username, password, email, firstname, lastname, join_date) VALUES ('$username', SHA('$password1'), '$email', '$fname', '$lname', NOW() )"; After INSERT INTO tuser the column names are used and after VALUES the input variables are used. Notice the password variable is inside SHA, SHA is a MySQL command to encrypt the data.

//query variable to insert user data
$query = "INSERT INTO tuser (username, password, email, firstname, lastname, join_date) VALUES ('$username', SHA('$password1'), '$email', '$fname', '$lname', NOW() )";

The query executes and the session signup is created, the signup session contains the sign up confirmation message. If the session is not started you will not be able to create any session containers. Remember, we started the session using "session_start();" in the header.php file.

//executes the query
 mysql_query($query);           

//The signup session is created, confirms success with user      
$_SESSION['signup'] = '<p class="message">Your new account has been sucessfully created. You\'re now ready to log in and edit your profile</a></p>';

After confirmation of a successful sign up, close the connection to the database, create the userid session, and redirect them to another page where they can log in. The code to close the database connection is, "mysql_close($link);" the link variable is the connection variable in the config.php file. You create the userid session for access control purposes, we will discuss that later. You use the header() function in PHP to redirect someone to another page. The PHP code for a redirect is, "header("Location: success.php");". In this guide you are redirected to the success.php page. After the redirect you use the php code, "exit();" which terminates the script.

//closes the connection to the database    
mysql_close($link);
         
//creates the session for the userid
$_SESSION['userid'] = "0";
         
//redirect to the PHP file success.php, on a successful log in
header('Location: success.php');

//terminates php script
exit();

We continue with the third if construct and add an else. If the number of rows with the username entered is not equal to 0, show the message that an account already exists with that username, you use the php echo to display the message.

if(mysql_num_rows($data) == 0)    {
       
     //PHP Code
     }
     else {
     
      //an account already exists for this username, so display error message
      echo'<p class="error">An account already exists for this username, Please use a different name</p>';
      
      //clear username variable so that the form is cleared
      $username="";
     }

The next line of code continues the second if construct and adds an elseif and an else to it. If the passwords do not match it will display a message. If information is missing, it will display a message that you need to fill out all the information to continue.

if(!empty($username) && !empty($password1) && !empty($password2) &&   ($password1 == $password2)) {
    
     }     
     elseif ($password1 != $password2)    {
     
     //show message if passwords do not match
      echo'<p class="error">The Passwords do not match</p>';
     }

     else   {

     //show message that information is missing
    echo'<p class="error">You must enter all information to sign up</p>';
     }

The last line and final line closes the connection to the database

mysql_close($link);

Full Code:
<?
 
 //Include database connection file
 require_once('config.php');
 
  
 //when the signup button is clicked, grab data from the form using POST
  if(isset($_POST['submit']))
  {

  //create the input variables and prevent SQL injection
   $username = mysql_real_escape_string($_POST['username']);
   $password1 = mysql_real_escape_string($_POST['password1']);
   $password2 = mysql_real_escape_string($_POST['password2']);
   $email = mysql_real_escape_string($_POST['email']);
   $fname = mysql_real_escape_string($_POST['fname']);
   $lname = mysql_real_escape_string($_POST['lname']);
   
   
   //check to make sure that none of the fields are empty and that the passwords match
   if(!empty($username) && !empty($password1) && !empty($password2) && ($password1 == $password2))
   {
  
    //make sure the username does not already exist, create sql query to check username
    $query = "SELECT * FROM tuser WHERE username = '$username' "; 
       
    $data = mysql_query($query);
    //the data variable connects to the database and executes the MySQL query

    //check to make sure no username row exists in the data, if data is empty or zero
    if(mysql_num_rows($data) == 0) 
      {
       
          //query variable to insert user data
          $query = "INSERT INTO tuser (username, password, email, firstname, lastname, join_date) VALUES ('$username', SHA('$password1'), '$email', '$fname', '$lname', NOW() )";
      
          //executes query above
          mysql_query($query);           

          //The signup session is created, confirms success with user      
          $_SESSION['signup'] = '<p class="message">Your new account has been sucessfully created. You\'re now ready to log in and edit your profile</a></p>';
        
         //closes the connection to the database    
         mysql_close($link);
         
         //creates the session for the userid
         $_SESSION['userid'] = "0";
         
         //redirect to the PHP file success.php, on a successful log in
         header('Location: success.php');
          
         //terminates php script
         exit();

      }
     else {
      //an account already exists for this username, so display error message
      echo'<p class="error">An account already exists for this username, Please use a different name</p>';
      
      //clear username variable so that the form is cleared
      $username="";
     }

   }
      
   elseif ($password1 != $password2) {   
    echo'<p class="error">The Passwords do not match</p>';
     
    }
   else {
    echo'<p class="error">You must enter all information to sign up</p>';
    }
   
    
  
  
  }
  
  mysql_close($link);
  
  
?>

Now that the sign up process is complete, part 3 will be about the log in process, and how to save a cookie.


4 comments:

Cristeen said...

fantastic post thanks for sharing
web agency brussels

software development company chennai tamilnadu india said...

good work.. that am doing software development company in chennai india and web site development company in chennai .

forcitute said...

Hi this is such a nice blog and hope u will provide some more new post over web designing really i got lot of info from here

Thanks

tessy rin said...

These articles and blogs are truly enough for me for a day.
search engine optimization

Post a Comment

Note: Only a member of this blog may post a comment.

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Bluehost Review