Sunday, July 31, 2016

How to Create a PHP/MySQL Powered Forum from Scratch_part2

Step 4: Displaying the Forum Overview

Since we're just started with some basic techniques, we're going to make a simplified version of the forum overview for now.
  1. <?php
  2. //create_cat.php
  3. include 'connect.php';
  4. include 'header.php';
  5.          
  6. echo '<tr>';
  7.     echo '<td class="leftpart">';
  8.         echo '<h3><a href="category.php?id=">
  9. Category name</a></h3>
  10.  Category description goes here';
  11.     echo '</td>';
  12.     echo '<td class="rightpart">';                
  13.             echo '<a href="topic.php?id=">
  14. Topic subject</a> at 10-10';
  15.     echo '</td>';
  16. echo '</tr>';
  17. include 'footer.php';
  18. ?>
There you have it: a nice and clean overview. We'll be updating this page throughout the tutorial so that it becomes more like the end result, step by step!

Step 5: Signing up a User

Let's start by making a simple HTML form so that a new user can register.


A PHP page is needed to process the form. We're going to use a $_SERVER variable. The $_SERVER variable is an array with values that are automatically set with each request. One of the values of the $_SERVER array is 'REQUEST_METHOD'. When a page is requested with GET, this variable will hold the value 'GET'. When a page is requested via POST, it will hold the value 'POST'. We can use this value to check if a form has been posted. See the signup.php page below.
  1. <?php
  2. //signup.php
  3. include 'connect.php';
  4. include 'header.php';
  5.  
  6. echo '<h3>Sign up</h3>';
  7.  
  8. if($_SERVER['REQUEST_METHOD'] != 'POST')
  9. {
  10.     /*the form hasn't been posted yet, display it
  11.       note that the action="" will cause the form to post to the same page it is on */
  12.     echo '<form method="post" action="">
  13.         Username: <input type="text" name="user_name" />
  14.         Password: <input type="password" name="user_pass">
  15.         Password again: <input type="password" name="user_pass_check">
  16.         E-mail: <input type="email" name="user_email">
  17.         <input type="submit" value="Add category" />
  18.      </form>';
  19. }
  20. else
  21. {
  22.     /* so, the form has been posted, we'll process the data in three steps:
  23.         1.  Check the data
  24.         2.  Let the user refill the wrong fields (if necessary)
  25.         3.  Save the data 
  26.     */
  27.     $errors = array(); /* declare the array for later use */
  28.      
  29.     if(isset($_POST['user_name']))
  30.     {
  31.         //the user name exists
  32.         if(!ctype_alnum($_POST['user_name']))
  33.         {
  34.             $errors[] = 'The username can only contain letters and digits.';
  35.         }
  36.         if(strlen($_POST['user_name']) > 30)
  37.         {
  38.             $errors[] = 'The username cannot be longer than 30 characters.';
  39.         }
  40.     }
  41.     else
  42.     {
  43.         $errors[] = 'The username field must not be empty.';
  44.     }
  45.      
  46.      
  47.     if(isset($_POST['user_pass']))
  48.     {
  49.         if($_POST['user_pass'] != $_POST['user_pass_check'])
  50.         {
  51.             $errors[] = 'The two passwords did not match.';
  52.         }
  53.     }
  54.     else
  55.     {
  56.         $errors[] = 'The password field cannot be empty.';
  57.     }
  58.      
  59.     if(!empty($errors)) /*check for an empty array, if there are errors,
  60.  they're in this array (note the ! operator)*/
  61.     {
  62.         echo 'Uh-oh.. a couple of fields are not filled in correctly..';
  63.         echo '<ul>';
  64.         foreach($errors as $key => $value)
  65.  /* walk through the array so all the errors get displayed */
  66.         {
  67.             echo '<li>' . $value . '</li>';
  68.  /* this generates a nice error list */
  69.         }
  70.         echo '</ul>';
  71.     }
  72.     else
  73.     {
  74.         //the form has been posted without, so save it
  75.         //notice the use of mysql_real_escape_string, keep everything safe!
  76.         //also notice the sha1 function which hashes the password
  77.         $sql = "INSERT INTO
  78.                     users(user_name, user_pass, user_email ,user_date, user_level)
  79.                 VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
  80.                        '" . sha1($_POST['user_pass']) . "',
  81.                        '" . mysql_real_escape_string($_POST['user_email']) . "',
  82.                         NOW(),
  83.                         0)";
  84.                          
  85.         $result = mysql_query($sql);
  86.         if(!$result)
  87.         {
  88.             //something went wrong, display the error
  89.             echo 'Something went wrong while registering. 
  90. Please try again later.';
  91.             //echo mysql_error(); //debugging purposes,
  92.  uncomment when needed
  93.         }
  94.         else
  95.         {
  96.             echo 'Successfully registered. 
  97. You can now <a href="signin.php">sign in</a> and start posting! :-)';
  98.         }
  99.     }
  100. }
  101.  
  102. include 'footer.php';
  103. ?>
A lot of explanation is in the comments I made in the file, so be sure to check them out. The processing of the data takes place in three parts:
  • Validating the data
  • If the data is not valid, show the form again
  • If the data is valid, save the record in the database
The PHP part is quite self-explanatory. The SQL-query however probably needs a little more explanation.
  1. INSERT INTO
  2.        users(user_name, user_pass, user_email ,user_date, user_level)
  3. VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
  4.        '" . sha1($_POST['user_pass']) . "',
  5.        '" . mysql_real_escape_string($_POST['user_email']) . "',
  6.        NOW(),   
  7.        0);
On line 1 we have the INSERT INTO statement which speaks for itself. The table name is specified on the second line. The words between the brackets represent the columns in which we want to insert the data. The VALUES statement tells the database we're done declaring column names and it's time to specify the values. There is something new here: mysql_real_escape_string. The function escapes special characters in an unescaped string , so that it is safe to place it in a query. This function MUST always be used, with very few exceptions. There are too many scripts that don't use it and can be hacked real easy. Don't take the risk, use mysql_real_escape_string().
"Never insert a plain password as-is. You MUST always encrypt it."
Also, you can see that the function sha1() is used to encrypt the user's password. This is also a very important thing to remember. Never insert a plain password as-is. You MUST always encrypt it. Imagine a hacker who somehow manages to get access to your database. If he sees all the plain-text passwords he could log into any (admin) account he wants. If the password columns contain sha1 strings he has to crack them first which is almost impossible.

Note: it's also possible to use md5(), I always use sha1() because benchmarks have proved it's a tiny bit faster, not much though. You can replace sha1 with md5 if you like.

If the signup process was successful, you should see something like this:


Try refreshing your phpMyAdmin screen, a new record should be visible in the users table.

Step 6: Adding Authentication and User Levels

An important aspect of a forum is the difference between regular users and admins/moderators. Since this is a small forum and adding features like adding new moderators and stuff would take way too much time, we'll focus on the login process and create some admin features like creating new categories and closing a thread.

Now that you've completed the previous step, we're going to make your freshly created account an admin account. In phpMyAdmin, click on the users table, and then 'Browse'. Your account will probably pop up right away. Click the edit icon and change the value of the user_level field from 0 to 1. That's it for now. You won't notice any difference in our application immediately, but when we've added the admin features a normal account and your account will have different capabilities.

The sign-in process works the following way:
  • A visitor enters user data and submits the form
  • If the username and password are correct, we can start a session
  • If the username and password are incorrect, we show the form again with a message
https://school.codequs.com/p/rJqQzyIO

The signin.php file is below. Don't think I'm not explaining what I'm doing, but check out the comments in the file. It's much easier to understand that way.
  1. <?php
  2. //signin.php
  3. include 'connect.php';
  4. include 'header.php';
  5. echo '<h3>Sign in</h3>';
  6. //first, check if the user is already signed in. If that is the case,
  7. there is no need to display this page
  8. if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
  9. {
  10. echo 'You are already signed in,
  11. you can <a href="signout.php">sign out</a> if you want.';
  12. }
  13. else
  14. {
  15. if($_SERVER['REQUEST_METHOD'] != 'POST')
  16. {
  17. /*the form hasn't been posted yet, display it
  18. note that the action="" will cause the form to post to the same page it is on */
  19. echo '<form method="post" action="">
  20. Username: <input type="text" name="user_name" />
  21. Password: <input type="password" name="user_pass">
  22. <input type="submit" value="Sign in" />
  23. </form>';
  24. }
  25. else
  26. {
  27. /* so, the form has been posted, we'll process the data in three steps:
  28. 1. Check the data
  29. 2. Let the user refill the wrong fields (if necessary)
  30. 3. Varify if the data is correct and return the correct response
  31. */
  32. $errors = array(); /* declare the array for later use */
  33. if(!isset($_POST['user_name']))
  34. {
  35. $errors[] = 'The username field must not be empty.';
  36. }
  37. if(!isset($_POST['user_pass']))
  38. {
  39. $errors[] = 'The password field must not be empty.';
  40. }
  41. if(!empty($errors)) /*check for an empty array, if there are errors,
  42. they're in this array (note the ! operator)*/
  43. {
  44. echo 'Uh-oh.. a couple of fields are not filled in correctly..';
  45. echo '<ul>';
  46. foreach($errors as $key => $value)
  47. /* walk through the array so all the errors get displayed */
  48. {
  49. echo '<li>' . $value . '</li>'; /* this generates a nice error list */
  50. }
  51. echo '</ul>';
  52. }
  53. else
  54. {
  55. //the form has been posted without errors, so save it
  56. //notice the use of mysql_real_escape_string, keep everything safe!
  57. //also notice the sha1 function which hashes the password
  58. $sql = "SELECT
  59. user_id,
  60. user_name,
  61. user_level
  62. FROM
  63. users
  64. WHERE
  65. user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
  66. AND
  67. user_pass = '" . sha1($_POST['user_pass']) . "'";
  68. $result = mysql_query($sql);
  69. if(!$result)
  70. {
  71. //something went wrong, display the error
  72. echo 'Something went wrong while signing in. Please try again later.';
  73. //echo mysql_error(); //debugging purposes, uncomment when needed
  74. }
  75. else
  76. {
  77. //the query was successfully executed, there are 2 possibilities
  78. //1. the query returned data, the user can be signed in
  79. //2. the query returned an empty result set, the credentials were wrong
  80. if(mysql_num_rows($result) == 0)
  81. {
  82. echo 'You have supplied a wrong user/password combination. Please try again.';
  83. }
  84. else
  85. {
  86. //set the $_SESSION['signed_in'] variable to TRUE
  87. $_SESSION['signed_in'] = true;
  88. //we also put the user_id and user_name values in the $_SESSION,
  89. so we can use it at various pages
  90. while($row = mysql_fetch_assoc($result))
  91. {
  92. $_SESSION['user_id'] = $row['user_id'];
  93. $_SESSION['user_name'] = $row['user_name'];
  94. $_SESSION['user_level'] = $row['user_level'];
  95. }
  96. echo 'Welcome, ' . $_SESSION['user_name'] . '.
  97. <a href="index.php">Proceed to the forum overview</a>.';
  98. }
  99. }
  100. }
  101. }
  102. }
  103. include 'footer.php';
  104. ?>
This is the query that's in the signin.php file:
  1. SELECT
  2.     user_id,
  3.     user_name,
  4.     user_level
  5. FROM
  6.     users
  7. WHERE
  8.     user_name = '" .
  9.  mysql_real_escape_string($_POST['user_name']) . "'
  10. AND
  11.     user_pass = '" . sha1($_POST['user_pass'])
It's obvious we need a check to tell if the supplied credentials belong to an existing user. A lot of scripts retrieve the password from the database and compare it using PHP. If we do this directly via SQL the password will be stored in the database once during registration and never leave it again. This is safer, because all the real action happens in the database layer and not in our application.

If the user is signed in successfully, we're doing a few things:
  1. <?php
  2. //set the $_SESSION['signed_in'] variable to TRUE
  3. $_SESSION['signed_in'] = true;                  
  4. //we also put the user_id and user_name 
  5. values in the $_SESSION, so we can use it at various pages
  6. while($row = mysql_fetch_assoc($result))
  7. {
  8.     $_SESSION['user_id'] = $row['user_id'];
  9.     $_SESSION['user_name'] = $row['user_name']; 
  10. }
  11. ?>
First, we set the 'signed_in' $_SESSION var to true, so we can use it on other pages to make sure the user is signed in. We also put the username and user id in the $_SESSION variable for usage on a different page. Finally, we display a link to the forum overview so the user can get started right away.

Of course signing in requires another function, signing out! The sign-out process is actually a lot easier than the sign-in process. Because all the information about the user is stored in $_SESSION variables, all we have to do is unset them and display a message.

Now that we've set the $_SESSION variables, we can determine if someone is signed in. Let's make a last simple change to header.php:

Replace:
  1. <div id="userbar">Hello Example. Not you? Log out.</div>
With:
  1. <?php
  2. <div id="userbar">
  3.     if($_SESSION['signed_in'])
  4.     {
  5.         echo 'Hello' . $_SESSION['user_name'] . '.
  6.  Not you? <a href="signout.php">Sign out</a>';
  7.     }
  8.     else
  9.     {
  10.         echo '<a href="signin.php">Sign in</a> or
  11.  <a href="sign up">create an account</a>.';
  12.     }
  13. </div>
If a user is signed in, he will see his or her name displayed on the front page with a link to the signout page. Our authentication is done! By now our forum should look like this:

https://school.codequs.com/p/rJqQzyIO

Step 7: Creating a Category

We want to create categories so let's start with making a form.

  1. <form method="post" action="">
  2.     Category name: <input type="text" name="cat_name" />
  3.     Category description: <textarea name="cat_description" /></textarea>
  4.     <input type="submit" value="Add category" />
  5.  </form>
This step looks a lot like Step 4 (Signing up a user'), so I'm not going to do an in-depth explanation here. If you followed all the steps you should be able to understand this somewhat quickly.

  1. <?php
  2. //create_cat.php
  3. include 'connect.php';
  4.  
  5. if($_SERVER['REQUEST_METHOD'] != 'POST')
  6. {
  7.     //the form hasn't been posted yet, display it
  8.     echo '<form method='post' action=''>
  9.         Category name: <input type='text' name='cat_name' />
  10.         Category description: <textarea name='cat_description' /></textarea>
  11.         <input type='submit' value='Add category' />
  12.      </form>';
  13. }
  14. else
  15. {
  16.     //the form has been posted, so save it
  17.     $sql = ìINSERT INTO categories(cat_name, cat_description)
  18.        VALUES('' . mysql_real_escape_string($_POST['cat_name']) . ì',
  19.              '' . mysql_real_escape_string($_POST['cat_description']) . ì')';
  20.     $result = mysql_query($sql);
  21.     if(!$result)
  22.     {
  23.         //something went wrong, display the error
  24.         echo 'Error' . mysql_error();
  25.     }
  26.     else
  27.     {
  28.         echo 'New category successfully added.';
  29.     }
  30. }
  31. ?>

As you can see, we've started the script with the $_SERVER check, after checking if the user has admin rights, which is required for creating a category. The form gets displayed if it hasn't been submitted already. If it has, the values are saved. Once again, a SQL query is prepared and then executed.

https://school.codequs.com/p/rJqQzyIO
                                                Source: tutsplus (countinue )
If you feel useful for you and for everyone, please share it!
Suggest for you:

Learning PHP 7: From the Basics to Application Development

The Complete PHP 7 Guide for Web Developers

Up to Speed with PHP 7

Learn PHP 7 This Way to Rise Above & Beyond Competion!

The Complete PHP with MySQL Developer Course (New)

No comments:

Post a Comment