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:

Building a social network: Functions(P2).

Introduction:

 In this section, I will help you to continue building the social network. Especially I will focus on the functions file that is a skeleton of the project.

Functions.php

<?php 
  $dbhost  = 'localhost';    // Unlikely to require changing
  $dbname  = 'your_database_name';   // Modify these...
  $dbuser  = 'your_username';   // ...variables according
  $dbpass  = 'your_password';   // ...to your installation
  $appname = "Qui's Nest"; // ...and preference

  $connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
  if ($connection->connect_error) die($connection->connect_error);

  function createTable($name, $query)
  {
    queryMysql("CREATE TABLE IF NOT EXISTS $name($query)");
    echo "Table '$name' created or already exists.<br>";
  }

  function queryMysql($query)
  {
    global $connection;
    $result = $connection->query($query);
    if (!$result) die($connection->error);
    return $result;
  }

  function destroySession()
  {
    $_SESSION=array();

    if (session_id() != "" || isset($_COOKIE[session_name()]))
      setcookie(session_name(), '', time()-2592000, '/');

    session_destroy();
  }

  function sanitizeString($var)
  {
    global $connection;
    $var = strip_tags($var);
    $var = htmlentities($var);
    $var = stripslashes($var);
    return $connection->real_escape_string($var);
  }

  function showProfile($user)
  {
    if (file_exists("$user.jpg"))
      echo "<img src='$user.jpg' style='float:left;'>";

    $result = queryMysql("SELECT * FROM profiles WHERE user='$user'");

    if ($result->num_rows)
    {
      $row = $result->fetch_array(MYSQLI_ASSOC);
      echo stripslashes($row['text']). "<br style='clear:left;'><br>";
    }
  }
?>

 As I mentioned in the introduction section, this file contains a little bit more than just the function, because I have added the database login details here instead of using another separate file. As you can see, the first half-dozen lines of code define the host, database name, username, and password of the database to use.
 It doesn't matter what you call the database. Also make sure to correctly assign a MySQL username and password to $dbuser and $dbpass. With correct values, the subsequent two lines will open a connection to MySQL and select the database. The last of the initial instructions sets the name of the social networking site by assigning the value Qui's Nest to the variable $appname. If you want to change the name, this is the place to do so.

Function Analysis:

   The project uses five main functions:
createTable - Checks whether a table already exists and, if not, creates it.
queryMysql - Issues a query to MySQL, outputting an error message if it fails.
destroySession - Destroys a PHP session and clears its data to log users out.
sanitizeString - Removes potentially malicious code or tags from user input.
showProfile - Displays a user’s image and “about me” message if he has one.

 All of these should be obvious in their action to you, with the possible exception of showProfile, which looks for an image of the name user.jpg (where user is the username of the current user), and if it finds it, displays it. It also displays any “about me” text the user may have saved.
  I have ensured that error handling is in place for all the functions that need it, so that they can catch any typographical or other errors you may introduce, and generate error messages. However, if you use any of this code on a production server, you will probably want to provide your own error-handling routines to make the code more user-friendly.

Conclusion:

 In this section, I helped you define the functions.php file that we will use in the project. Although this file won't display any content in the site, it is really important to do almost main functions such as database connection and creation, session creation, error prevention, and showProfile definition.

* Ref:
strip_tags
htmlentities
stripslashes
real_escape_string
fetch_array

Tuesday, April 5, 2016

Building a social network: Introduction(P1).

Introduction:
 Have you ever asked yourself that how Facebook, Twitter or Instagram were built? How can Mark Zuckerberg build the Facebook? Can I do one for myself? What things do I need to learn in order to build them? My answer for these questions is that you can do it if you are really desired to learn about it. In this project I'll guide you how to build a social network by using PHP and MySQL. Because this tutorial is quite long so I will divide it into many parts. The result for this project:http://socialnetworks.16mb.com and the demo as below:



Requirements:
- In order to understand this project it requires you to have a solid knowledge about PHP and MySQL as well as a basic understanding about HTML, CSS and AJAX.


Design a social network site:
 There are a couple of things that we need to plan before we build a social network:
- A sign-up process
- A login form
- A logout facility
- Session control
- User profiles with uploaded thumbnails
- A member directory
- Adding members as friends
- Public and private messaging between members
- How to style the project
This project includes several code files:
1. functions.php - includes functions + database login.
2. header.php - this file is included by other files so each page of the project can be accessed to the same features for uniformity.
3. setup.php - creates MySQL tables. This file needs to be executed first to setup initial database.
4. index.php - home page. Display a simple welcome message.
5. signup.php - sign up page. Enable users to join the network.
6. checkuser.php - check whether creating username is duplicated with existing users in database or not.
7. login.php - sign in page. Authenticate user's login.
8. profile.php - create a profile.
9. members.php - list of members you can find and add as friends (or drop if already friends).
10. friends.php - list of mutual friends, followers and following users.
11. messages.php - messages are posted in public or private mode.
12. logout.php - logout the site.
13. style.css - layout the site.
14. javascript.js - contains some functions for scripting and combines with HTML5 to draw the logo.

Conclusion:
 In this section I just introduced some ideas about our project. I hope that you have an image of how our project looks like. I will dive into the project next sections.