Tuesday, April 12, 2016

Building a social network: login(P8).

Introduction:

  In this section, I will guide you how to create a login.php file which is used for user sign in the site. This file is not much different from the signup.php file. So, it will not be so difficult for you to understand if you have already read the previous sections. 

 login.php:

<?php 
  require_once 'header.php';
  echo "<div class='main'><h3>Please enter your details to log in</h3>";
  $error = $user = $pass = "";

  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");
         $token    = substr($token, 0,16);

    if ($user == "" || $pass == "")
       $error = "<span class='error'>Not all fields were entered</span><br><br>";
    else
    {

      $result = queryMySQL("SELECT * FROM members WHERE user='$user'");

      if ($result->num_rows == 0)
      {
        $error = "<span class='error'>Username/Password
                  invalid</span><br><br>";
      }
      else
      {
         $row = $result->fetch_array(MYSQLI_NUM);
         $result->close();
        if ($token == $row[1]) {
        $_SESSION['user'] = $user;
        $_SESSION['pass'] = $pass;

        die("You are now logged in. Please <a href='members.php?view=$user'>" .
            "click here</a> to continue.<br><br>"); 
        }
        else  $error = "<span class='error'>Username/Password
                  invalid</span><br><br>";
      }
    }
  }
  echo <<<_END
    <form method='post' action='login.php'>$error
    <span class='fieldname'>Username</span><input type='text'
      maxlength='16' name='user' value='$user'><br>
    <span class='fieldname'>Password</span><input type='password'
      maxlength='16' name='pass' value='$pass'>
_END;
?>
    <br>
    <span class='fieldname'>&nbsp;</span>
    <input type='submit' value='Login'>
    </form><br></div>
  </body>
</html>
  Like the sign-up page, it features a simple HTML form and some basic error checking, as well as using  sanitizeString  before querying the MySQL database.
  The main thing to note here is that, upon successful verification of the username and password, the session variables user and pass are given the username and password values. As long as the current session remains active, these variables will be accessible by all the programs in the project, allowing them to automatically provide access to logged-in users.
  One thing we need to consider is that we repeated hashing the password as the same way we did in the signup.php file and checked to see whether hashed password ($token with fixed length:16) is matched with the value which was stored in the database or not. If it is matched we start the new sessions with username and password that the user has just typed to login the site. Otherwise an error message will be displayed "Username/Password invalid" as below:
Fig 1. Failed login.

 You may be interested in the use of the die function upon successfully logging in. This is there because it combines an echo and an exit command in one, thus saving a line of code. For styling, this (and most of the files) applies the class main to indent the content from the left-hand edge.
  When you successfully login the site, it should look like Figure 2.
  
Fig. 2. Successful login.
   Conclusion:
    
     In this section, I helped you build the login.php file used for user to login the site. In the next section I will help you to create the profile.php file. I hope that you can find some useful information in this section.

 * Ref:
   substr

Monday, April 11, 2016

Building a social network: checkup(P7).

Introduction:

 To go with signup.php I will continue introducing you how to write code for checkup.php file which  is used to look up the username in the database and returns a string indicating whether it has been already been taken. 

checkup.php

<?php 
  require_once 'functions.php';

  if (isset($_POST['user']))
  {
    $user   = sanitizeString($_POST['user']);
    $result = queryMysql("SELECT * FROM members WHERE user='$user'");

    if ($result->num_rows)
      echo  "<span class='taken'>&nbsp;&#x2718; " .
            "This username is taken</span>";
    else
      echo "<span class='available'>&nbsp;&#x2714; " .
           "This username is available</span>";
  }
?>

  As we can see, it relies on the functions sanitizeString and queryMysql. Therefore, the program first includes the file functions.php. 
 Then, if the $_POST variable user has a value, the function looks it up in the database and, depending on whether it exists as a username, outputs either “This username is taken” or “This username is available.” Just checking the function mysql_num_rows against the result is sufficient for this, as it will return  0  for not found, or 1 if it is found.   
 The HTML entities &#x2718; and &#x2714; are also used to preface the string with either a cross or a checkmark. Below is an example new user creates an account which is already existed in the database.

Fig. 1. Duplicated account error.

  Conclusion:

  In this section I helped you to write code for checkup.php file combined with signup.php file to do checking and creating a new user account for the site. I hope that you can find useful information in this section.
   

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: