Sunday, April 10, 2016

Building a social network: signup(P6).

 Introduction:

   In this section, I continue to introduce you about how to build a social network. You will learn how to write code to help new user creating his/her account. Therefore it will enable them to login to the site. 

signup.php


<?php 
  require_once 'header.php';

  echo <<<_END
  <script>
  function checkUser(user)
  {
  if (user.value == '')
  {
    O('info').innerHTML = ''
    return
  }

  params  = "user=" + user.value
  request = new ajaxRequest()
  request.open("POST", "checkuser.php", true)
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
  request.setRequestHeader("Content-length", params.length)
  request.setRequestHeader("Connection", "close")

  request.onreadystatechange = function()
  {
    if (this.readyState == 4)
      if (this.status == 200)
        if (this.responseText != null)
          O('info').innerHTML = this.responseText
  }
  request.send(params)
  }

  function ajaxRequest()
  {
  try { var request = new XMLHttpRequest() }
  catch(e1) {
    try { request = new ActiveXObject("Msxml2.XMLHTTP") }
    catch(e2) {
      try { request = new ActiveXObject("Microsoft.XMLHTTP") }
      catch(e3) {
        request = false
  } } }
  return request
  }
  </script>
  <div class='main'><h3>Please enter your details to sign up</h3>
_END;

  $error = $user = $pass = "";
  if (isset($_SESSION['user'])) destroySession();
  if (isset($_POST['user']) && isset($_POST['pass']))
  {
    $user = sanitizeString($_POST['user']);
    $pass = sanitizeString($_POST['pass']);
    $salt1    = "qm&h*";
    $salt2    = "pg!@";
    $token    = hash('ripemd128', "$salt1$pass$salt2");
    if ($user == "" || $pass == "")
      $error = "Not all fields were entered<br><br>";
    else
    {
      $result = queryMysql("SELECT * FROM members WHERE user='$user'");

      if ($result->num_rows)
        $error = "That username already exists<br><br>";
      else
      {
        queryMysql("INSERT INTO members VALUES('$user', '$token')");
        die("<h4>Account created</h4>Please Log in.<br><br>");
      }
    }
  }
  echo <<<_END
    <form method='post' action='signup.php'><span style="color:red;">$error</span>
    <span class='fieldname'>Username</span>
    <input type='text' maxlength='16' name='user' value='$user'
      onBlur='checkUser(this)'><span id='info'></span><br>
    <span class='fieldname'>Password</span>
    <input type='password' maxlength='16' name='pass'
      value='$pass'><br>
_END;
?>
    <span class='fieldname'>&nbsp;</span>
    <input type='submit' value='Sign up'>
    </form></div><br>
  </body>
</html>
  Let’s start by looking at the end block of HTML. This is a simple form that allows a username and password to be entered. But note the use of the empty span given the id of 'info'. This will be the destination of the Ajax call in this program that checks whether a desired username is available.

Checking for Username Availability
 
  Now go back to the program start and you’ll see a block of JavaScript that starts with the function checkUser. This is called by the JavaScript onBlur event when focus is removed from the username field of the form. First it sets the contents of the span I mentioned (with the id of info) to an empty string, which clears it in case it previously had a value.
 Next a request is made to the program checkuser.php, which reports whether the username user is available. The returned result of the Ajax call, a friendly message, is then placed in the info span. Moreover, this section also uses the sanitize String function to remove potentially malicious characters before looking up the username in the database and, if it’s not already taken, inserting the new username $user and $token. For security purpose I already salted the password and stored it as one-way hash strings. That's why the $token is inserted into the database instead of the $pass. You can see the hash strings format stored in the database as below:

Fig 1. The hash strings format.

 Logging In
  
  Upon successfully signing up, the user is then prompted to log in. A more fluid response at this point might be to automatically log in a newly created user, but, as I don’t want to overly complicate the code, I have kept the sign-up and login modules separate from each other. You can easily implement this if you want to, however. This file uses the CSS class fieldname to arrange the form fields, aligning them neatly under each other in columns. When loaded into a browser (and in conjunction with checkuser.php, shown later in the next section), this program will look like Figure 2, where you can see that the Ajax call has identified that the username andrew is available. 
Fig 2. Sign up page
    Conclusion:
   
  In this section I helped you build the signup page used to register the new user account. It will be much easier for you to follow the code if you have a basic knowledge about AJAX. I hope that you can learn something new in this section. 

* Ref:

No comments:

Post a Comment