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:

Saturday, April 9, 2016

Building a social network: index(P5).

Introduction:

  In this section, I will introduce you the index.php which is also the default page when users access to the website. This is one of the simplest code files in our project. This file is a trivial file but necessary nonetheless to give the project a home page. All it does is display a simple welcome message. In a finished application, this would be where you sell the virtues of your site to encourage sign-ups. Now, are you ready to discover the index.php file? if yes, get started! if you are not ready yet, get started too!

index.php

<?php
   require_once 'header.php';
  echo "<br><span class='main'>Welcome to $appname,";
  if ($loggedin) echo " $user, you are logged in.";
  else           echo ' please sign up and/or log in to join in.';
?>
    </span><br><br>
  </body>
</html>

 Incidentally, seeing as all the MySQL tables have been created and the include files saved, you can now load index.php , into your browser to get your first peek at the new application. It should look like as below:


Fig 1. The main page of the site

Conclusion:
  
   In this section I have shown you the simple code to construct the home page. In the next section I will help you to setup the signup.php file which is more complex than this. It also requires you to have knowledge about AJAX. However, before taking a new journey to there let's take a deep breath! 


Building a social network: setup(P4).

Introduction:

  In this section, I will guide you how to create database tables for our project by using SQL commands sent from web server to MySQL server. We do this with setup.php file which you should type and load into your browser before calling up any other files; otherwise, you’ll get numerous MySQL errors.

setup.php
 <!DOCTYPE html>
<html>
  <head>
    <title>Setting up database</title>
  </head>
  <body>
    <h3>Setting up...</h3>
<?php
  require_once 'functions.php';

  createTable('members',
              'user VARCHAR(16),
              pass VARCHAR(16),
              INDEX(user(6))');
  createTable('messages',
              'id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
              auth VARCHAR(16),
              recip VARCHAR(16),
              pm CHAR(1),
              time INT UNSIGNED,
              message VARCHAR(4096),
              INDEX(auth(6)),
              INDEX(recip(6))');
  createTable('friends',
              'user VARCHAR(16),
              friend VARCHAR(16),
              INDEX(user(6)),
              INDEX(friend(6))');
  createTable('profiles',
              'user VARCHAR(16),
              text VARCHAR(4096),
              INDEX(user(6))');
?>
    <br>...done.
  </body>
</html>
   The tables created are short and sweet, and have the following names and columns:
• members: username user (indexed), password pass
• messages: ID id (indexed), author auth (indexed), recipient recip, message type pm, message message
• friends: username user (indexed), friend’s username friend
• profiles: username user (indexed), “about me” text
Because the function  createTable first checks whether a table already exists, this program can be safely called multiple times without generating any errors. 
   It is very likely that you will need to add many more columns to these tables if you choose to expand on this project. If so, you may need to issue a MySQL DROP TABLE command before re-creating a table.
    After successfully creating the MySQL tables, the result is below:


Fig. 1. members table


Fig. 2. messages table


Fig. 3. friends table


Fig. 4. profile table

  Congratulations! You have just successfully created tables for our project. These are considered as our database to store users account, messages and profile. 

   Conclusion:

     In this section, I have shown you how to create MySQL tables. By excuting several simple SQL commands we easily created them. It is a bit of cake, isn't it? 

* Ref:

Building a social network: Header(P3).

Introduction:

In this section, I will introduce the header.php file that each page of the project will need to have access the same set of features. This file is actually included by the other files and it includes functions.php file. This means that only a single require_once is needed in each file.

header.php

<?php
session_start();
  echo "<!DOCTYPE html>\n<html><head><link rel='icon' href='robin.gif' 
type='image/gif' sizes='16x16'>";
  require_once 'functions.php';
  $userstr = ' (Guest)';
  if (isset($_SESSION['user']))
  {
    $user     = $_SESSION['user'];
    $loggedin = TRUE;
    $userstr  = " ($user)";
  }
  else $loggedin = FALSE;
  echo "<title>$appname$userstr</title><link rel='stylesheet' " .
       "href='styles.css' type='text/css'>"                     .
       "</head><body><center><canvas id='logo' width='624' "    .
       "height='96'>$appname</canvas></center>"             .
       "<div class='appname'>$appname$userstr</div>"            .
       "<script src='javascript.js'></script>";
  if ($loggedin)
  {
    echo "<br ><ul class='menu'>" .
         "<li><a href='members.php?view=$user'>Home</a></li>" .
         "<li><a href='members.php'>Members</a></li>"         .
         "<li><a href='friends.php'>Friends</a></li>"         .
         "<li><a href='messages.php'>Messages</a></li>"       .
         "<li><a href='profile.php'>Edit Profile</a></li>"    .
         "<li><a href='logout.php'>Log out</a></li></ul><br>";
  }
  else
  {
    echo ("<br><ul class='menu'>" .
          "<li><a href='index.php'>Home</a></li>"                .
          "<li><a href='signup.php'>Sign up</a></li>"            .
          "<li><a href='login.php'>Log in</a></li></ul><br>"     .
          "<span class='info'>&#8658; You must be logged in to " .
          "view this page.</span><br><br>");
  }
?>
 As we see, this file starts by calling the function session_start. This sets up a session that will remember certain values we want to store across different PHP files. With the session started, the program then checks whether the session variable user is currently assigned a value. If so, a user has logged in and the variable $loggedin is set to TRUE.
 After the main setup code in which a style sheet is loaded, a canvas element is created for the logo, and a div is also created. The file  javascript.js is loaded to pull in the  O,  S, and  C functions which are short forms are used to select HTML elements by Id or class name. 
 Using the value of  $loggedin, an  if block displays one of two sets of menus. The non-logged-in set simply offers options of Home, Sign up, and Log in, whereas the logged-in version offers full access to the project’s features. Additionally, if a user is logged in, his or her username is appended in brackets to the page title and placed after the main heading. We can freely refer to $user wherever we want to put in the name, because if the user is not logged in, that variable is empty and will have no effect on the output.
  The styling applied to this file is in the file  styles.css and includes creating a wide heading with a colored background, and turning the links in the lists to rounded buttons.

Conclusion:

  In this section, I helped you build the header.php file included in almost other php files in our project. This file actually defines menus, logo for the site regardless user already logins the site or not.
* Ref: