mdinfotech.net  



This unit consists of two major components:
  1. Individual Exercises

  2. Listed below. 100/80/60 Quizzes will be given.


  3. Group project (20% of final mark)

  4. In groups, you will develop a dynamic website. This project will continue throughout the whole unit. Details will be given soon.
  1. Do this exercise: Using Linux and SFTP through SSH
  2. As always, everything from this section will be tested on.
Read Why Learn PHP?

After getting an account on the Linux server, upload a PHP Hello World file and run the script through a browser.

echo "Hello World!"
  1. Go to w3 Schools PHP Tutorials,
  2. Using the menu on the left side of the tutorials, complete all these PHP tutorials: PHP Intro, PHP Syntax, PHP Comments, PHP Variables, PHP Echo / Print, PHP Data Types, PHP Strings, PHP Numbers, PHP Math, PHP Constants, PHP Operators, PHP If...Else...Elseif, PHP Switch, PHP Loops, PHP Functions, PHP Sorting Arrays.
  3. Use any text editor to write your code.
  4. You can test it on the Linux server, or here: PHP Sandbox.
Important Resources
  1. Online PHP Parser - see if you have any errors
  2. PHP.net - the API for PHP
  3. w3 Schools PHP Tutorials - simple tutorials
You will need to be comfortable using HTML and CSS in this unit. If needed, visit the w3Schools HTML Tutorials and w3Schools CSS Tutorial to review.
  • PHP Superglobals at w3schools
  • include command at php.net
  • Watch Ms. Wear's video lesson on how to do this assignment:
    https://www.youtube.com/watch?v=Trqh1ZXo2AA.

    Your Task:
    Break a valid HTML5 template up into 3 files: header.inc, content.inc and footer.inc. Use the PHP command include to generate a valid html page with the content "Hello World!". Then create content2.inc and content3.inc. The content, and the page title, of content2 and content3 should be unique. Use an if statement to enable your php file to dynamically display 3 different pages based on the $_GET array.
    Resources
  • Valid HTML5 Template
  • HTML Validator
  • Use these resources to complete this project:
    1. Create a basic HTML form with the following elements:
      • a textbox for the user's name labelled: "First Name"
      • a textbox for the user's name labelled: "Last Name"
      • a file upload field labelled: "Profile Pic"
      • four radio buttons labelled: "Current Grade" with one radio button option for each grade 9-12
      • check boxes titled "Courses I Can Tutor" with a check box with 4 academic courses offered at Mt Doug (eventually this will be a list of all the courses at Mount Doug, but you need to know PHP and JSON first)
      • a textarea titled "About Me" where the user can put a blurb about who they are
      • a submit button which submits the form using POST
    2. Validate your HTML
    3. Now take your code from In class Exercise: My First Dynamic Website and:
      1. rename one of your .inc files form.inc,
      2. put the html header code from the form in header.inc, (everything from the first line down and including the body tag)
      3. put the html footer code from the form in footer.inc, (probably just closing tags for body and html)
      4. and put the code for the form in form.inc.
      5. rename hello.php to index.php
      6. update the code in index.php so the home page is not the form, but the form can be easily reached from the navigation bar.
    4. Upload to the Linux Server and save in a folder called tutormd1.
    5. To hand in: Ms. Wear will check it in class.
    Modify TutorMD 1 so that PHP is used to process the form data. Modify your project so that:
    1. Save this version of the project on the Linux Server in a folder called tutormd2
    2. when form.inc is successfully submitted, it shows a var_dump of the form data on home.inc.

    3. it requires all elements of the form EXCEPT PROFILE PIC to be completed
    4. it validates all the contents of the form EXCEPT PROFILE PIC
    5. if the content is not valid, it reloads the form with the contents still in it AND appropriate error messages.
    Follow all of these tutorials VERY CLOSELY while you do this exercise:
    1. Using Get vs Post.
    2. Form Validation
    3. Required Form Elements
    4. Validating Textboxes, Checkboxes, and Radio Buttons.
      The only one missing from this is TextArea. See if you can figure out how to validate it by looking at the var_dump (also print_r) of the $_POST array. Also note his use of trim to clean the data. Make sure you also use trim.
    5. Keep the Values in the form
    The Structure of Index.php
    1)  include functions.inc if that's a thing
    2) declare all variables
    3) if the form was submitted, validate it
    4) include the header, 
    5) if the form was submitted with errors show form
    6)  else if the form was submitted successfully show home and home will show the var_dump of POST
    7) else if one of the links was clicked show that page
    8) else show home.inc
    9) include  footer
    
    
    

    Assessment: It must meet all the criteria listed above.

    To hand in: Ms. Wear will mark it in class.

    Considerations:
    • Validate the form contents at the top of index.php. See w3 Complete Form Demo to see how to determine if the form was submitted.
    • Use this method from the w3 tutorial to clean the data from the text boxes, and text areas as it comes in from the form:
      function cleandata($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
      }
      
      Use it to clean the post array data like this:
      $_POST「"fname"」= cleandata($_POST「"fname"」) 
      

    In this exercise, you will add one piece of functionality to TutorMD: you will save the data from the form submissions into a text file using JavaScript Object Notation.

    First, restructure the course data to look something like this:

        $allCourses = array( "cs11" => "Computer Science 11", 
                             "cs12" => "Computer Science 12",
                             "apcs" => "AP Computer Science",
                             etc
                     );
        

    Each course should have a key that is a unique identifier. Rewrite your check boxes so that a foreach loop creates a checkbox for each item in the $allCourses array that uses the key as the HTML value and the full course name as the displayed name. For example, the first element in the array would look like this: check box

    **Note: all square brackets in the code below are images and will not copy and paste, you will need to type them in manually.

    Introducing JavaScript Object Notation (JSON)

    JavaScript Objects can be defined using an object literal notation like this:

    let person = {
      firstName: "John",
      lastName: "Doe",
      age: 50,
      eyeColor: "blue"
    };

    When this notation is used to store and exchange data it is known as JavaScript Object Notation or JSON. JSON uses JavaScript syntax, but the JSON format is text only. For this project, we will be storing the data from each form submission in JSON format. The advantage of using JSON is that both PHP and JavaScript have easy to use built in functions that will parse JSON and convert program data into JSON.

    Do this: Read Working with JSON.

    Write the Form Data to a JSON File

    In order to write the form data to JSON, you will need this PHP function: json_encode. To read convert a JSON string to a PHP array, you will need this PHP function: json_decode.

    PHP.net

    Note: Both these links are at php.net, which is the API for PHP. Go here anytime you need to look up a PHP function. It is often very helpful to read the comments at the bottom of the documentation for a specific function to see effective ways of using it.

    Your job is to save all form submissions to a master data file called userprofiles.json. After 4 submissions, your data file might look something like this:

    Sample JSON file
    **Note: all square brackets in the data are images and will not copy and paste, you will need to type them in manually.

    
    
        {
            "firstname": "Suzy",
            "lastname" : "Smith",
            "grade": "11",
            "about": "Like to chill and hang with my gal pals, and love my little pony.",
            "courses": "cs11", "cs12", "apcs"
        },
        {
            "firstname": "Boyang",
            "lastname" : "Chen",
            "grade": "12",
            "about": "3 years experience tutoring.",
            "courses": "phys11", "cs12", "apcs"
        },
        {
            "firstname": "Binita",
            "lastname" : "Jiao",
            "grade": "10",
            "about": "Available any time after school",
            "courses":"math09", "cs12", "apcs"
        },
        {
            "firstname": "Laura",
            "lastname" : "Folton",
            "grade": "12",
            "about": "Strong in the arts",
            "courses":"art9", "art10", "medart12"
        }
    
    
    

    Adding New Data to the JSON File

    This should be placed near the top of index.php. To add newly submitted form data to the json file:
    1. Open the existing file
    2. Read the file and decode the JSON into a PHP array
    3. Add the new form submission to the php array
    4. Convert the array back into JSON
    5. Write the JSON back to the file

    To save data to a file in PHP, use file_put_contents. If the file doesn't exist, it will be created. To read data from a file in PHP, use file_get_contents() - reads a file into a string.

    (The code to complete most of these tasks is provided below.)

    Permissons: In order to save the JSON data in a file, you will also need to know about ownership on the server. Any php script on the server runs because a client has made a request that is handled by the web server. The web server is considered a user on the server, with the user name www-data. Therefore, when your script creates a file on the server, it has www-data as the owner and the group, which means your username will not be able to edit or delete the file through WinSCP. The way to deal with this is to have your php script create the file if it doesn't already exist. Fortunately, file_put_contents deals with this.

    PHP to Open the JSON file and Convert it to PHP Array

     // read json file into array of strings
     $file = "userprofiles.json";
     $jsonstring = file_get_contents($file);
    
     //decode the string from json to PHP array
     $phparray = json_decode($jsonstring, true);
    
    Add the newly submitted form data to the array, convert array to JSON, and save back to file

     // add form submission to data
     $phparray = $_POST;
    
     // encode the php array to formatted json 
     $jsoncode = json_encode($phparray, JSON_PRETTY_PRINT);
     
     // write the json to the file
     file_put_contents($file, $jsoncode); 
      
    

    Fixing Corrupt Data

    While writing this project, you will no doubt write corrupt data to the json file. The solution to corrupt data is to delete the file and start over. Since www-data own the file, www-data must also delet the file. Add a link to your user interface that allows you to easily delete the file. The easiest way to do this is to pass a value to $_GET through the URL,
    delete json
    and if it's set, use the PHP method unlink to delete the file. This should be placed near the top of index.php:

    if (isset($_GET"action") && $_GET"action" == "del") {
        unlink("userprofiles.json");
    }
    
    The Structure of Index.php
    **bold indicates the minimum of what must be added to TutorMD 2. You will also need to add conditional statements to remove warnings from PHP.
    1) include functions.php if that's a thing
    2) declare all variables
    3) if the form was submitted, validate it
    4) if the form was submitted successfully, write the data to the file
    5) include the header, 
    6)  if the form was submitted with errors show form
    7) else if the form was submitted successfully show home
    8) else if one of the links was clicked show that page
    9) else show home.inc...home.inc needs to open the file and read it
    10)include  footer
    
    
    

    What to do for this assignment:

    1. Use the $allCourses array and a foreach loop to generate one checkbox for each course at Mount Doug.
    2. Add submitted form contents to the master data file called userprofiles.json in JSON format.
    3. Modify home.inc so that:
      • it reads in the contents of userprofiles.json into a PHP array
      • it show a var_dump of all the PHP array read in from the previous step.
    4. Add a link to home.inc that says "Delete JSON File" that deletes the JSON file (for when you need to start clean).

    Assessment: It must meet all the criteria listed above.

    To hand in: I will mark it by going to the url http://142.31.53.220/~yourname/tutormd3.

    PHP Debugging Hints:

    You are now getting into some serious PHP, and the error messages you get from the server may not be enough to find your bugs. Here is the order in which to do things when your code is not working:
    1. Did you actually save your changes in the text editor?
    2. Did you actually upload your changes? In WinSCP, on the server side of the file manager, right click and choose "refresh". Check the time stamp on the files on the server match the time stamp on the files on your local machine.
    3. Use Empty Cache and Reload to make sure the browser updated the files from the server and isn't using files from browser cache.
    4. Read your code carefully. Did you forget the $ in front of a variable name? Did you accidently use Java syntax instead of PHP syntax? Run it through theOnline PHP Parser to find syntax mistakes.

    In this part of the Tutor MD, you are going to add two pieces of functionality:

    1. you will enable image uploading
    2. and you will be using a Unique Identifier to ensure each form submission can be uniquely identified.

    The Lesson

    Watch Ms. Wear's Video on How to Upload a File with PHP. Use this tutorial for your code base w3 Uploading Files with PHP and read the tutorial very carefully.

    Note: To delete the images properly, replace the code from the video that looks like this:

    if (isset($_GET"delete")) {
       rmdir($target_dir);
    }
    with this:
    $dir = "profileimages/";
    if (isset($_GET"delete")) {  
      if ($dh = opendir($dir)){
        while (($file = readdir($dh)) !== false){
          if ($file != "." && $file != "..")
              unlink($dir . $file);
        }
        closedir($dh);
      }
    }

    What to do for this assignment:

    1. Make the file field required in the form.
    2. Save appropriate images uploaded using the form to the server
      • Save images in a folder called profileimages.
      • If profileimages does not exist, your script should create it. Look up mkdir.
      • Appropriate images include formats png and jpg and images 4 MB or under.
      • If a user attempts to upload a file that does not meet the criteria, display a descriptive error in the form beside the image upload field, and retain other form values.

    3. Use a unique identifier or UID.
      • Use the UID as the file name of the uploaded image. For example, the first image ever uploaded might be named 1.png, and the second image uploaded is called 2.jpg etc. Hint: a good way to keep track of the next identifier to use is to store it in a text file called identifier.txt that contains just the number to use for the next uploaded file name.
      • Add the unique identifier to the JSON data for this image. A good key would be UID because UID stands for Unique IDentifier.

    4. Add the file extension of the image file to the JSON data. For example the key value pair may be "imagetype":"png"

    5. Hint: Add imagetype and uid to the post array before writing it to the JSON array. This can be achieved just by doing this:
      $_POST「"imagetype"」= "jpg";
      $_POST「"uid"」= 123;
      
    6. On the home page,
      • Show all the images in profileimages below a var_dump of userprofiles.json. You will need read_dir.
      • Add a link that says "Delete All Entries" that deletes all the JSON data AND the uploaded images. Look up read_dir.
    With the new file information added, each form entry will look something like this:
                     
       {
            "firstname": "Boyang",
            "lastname" : "Chen",
            "grade": "12",
            "about": "3 years experience tutoring.",
            "courses": "phys11", "cs12", "apcs",
            "UID": "1",
            "imagetype": "png"
        }
         
                     

    Assessment:

    It must meet all the criteria listed above.

    To hand in:

  • Save this version of the project on the Linux Server in a folder called tutormd4
  • .

    For this exercise, use the code provided in Wear_IT\Pick-Up\CompSci12\Light Box Base Code

    To display JSON data in the lightbox, you must get displayLightBox to fetch the JSON data from the server. These are instructions on how to do that.

    1. Write a new PHP script called getData.php with the following functionality:
      // getData.php
      //use $_GET array to get the value of the requested uid
      // open json file, load contents into $phparray, and use a loop to 
      // find an element with the matching uid
      // echo the element of the php array with the matching uid
      // something like this echo json_encode($phparray$i);
      			
      Now test this script works with a browser. For example, the this URL
      http://142.31.53.220/~yourname/tutormd5/getData.php?uid=2
      
      should display the JSON for the element with the uid = 2.
    2. Since your thumbnail images will be named 1.jpg, 2.png, etc, you can use the name of the file to get the UID of the image that has been clicked. Since the image name is a parameter for the function displayLightBox, use the JS function split on imageFile to get the uid of the image and save it in a variable called requestedUid.
    3. In displayLightBox, use the fetch command to get the JSON for a given uid from getData.php.
       if (imageFile != "") {
         fetch ("http://142.31.53.220/~yourname/tutormd5/getData.php?uid=" + requestedUid)
          .then(response => response.json())
          .then(data => updateContents(data))
          .catch(err => console.log("error occurred " + err));
       }
       
      and add this function
       function updateContents(data) {
          console.log(data);
       }
       
      Now test that it works. When you click on a thumbnail, the JSON for that image should appear in the console.
    4. Now display the JSON info in the lightbox. Somewhere in the lightbox create a div tag with the id name and add this CSS
      #name {
        color:yellow;
        border:thick solid red;
        width: 100px;
      }
      
      and add this JS to updateContents
      document.getElementById("name").innerHTML = data.name;
      As long as the name of the user is stored in JSON with the key name, this should load the profile's name in the Lightbox.
    5. Now make it look good :)

    In this version, we are adding a number of improvements.

    Add the following functionality to TutorMD:
    1. Create thumbnails: After an image is saved to the server (after being uploaded from the form), create a 240x240 pixel thumbnail of the image in a separate folder called thumbnails.
      You will need to include this code: createthumbnail.php. Run this test program first to make sure your permissions are set up correctly.
    2. Make home show a grid of thumbnails:
      Keep it simple for now. Styling it will happen in the final project. Basically use a for loop to read the thumbnails folder and generate the html that displays a grid of clickable images.
      thumbnails example
    3. Add a LightBox:
      • If a user clicks a thumbnail, it loads a light box with a larger version of the image. Use the code provided in Wear_IT\Pick-Up\CompSci12\Light Box Base Code
      • See the lesson before this one for more info.
      • Display the name of the user, their grade, and their about me, and a list of the courses they tutor.
      • When the page initially loads, it should only load thumbnail images. When a thumnail is clicked, it will load the large version of the image. Note: this is what the CS 11 Lightbox code does.
      • Add download button on the lightbox view of each image that results in just that one image being downloaded. Use this tutorial HTML5 Download Links.
      lightbox
    4. User Controls: Create a navigation bar that is part of header.inc. Include:
      • a "Become a Tutor" link or button which takes the user to the form
      • a "View Profiles" link or button which returns to the home page
      • a "Reset Gallery" button or link which deletes all the images, thumbnails, and the json data with one click. Remove any previous "Delete Images" and "Delete Json" links you have left over from previous assignments.
      • a Download All link or button that creates a zip file of all the images and downloads it to the client's computer.
        You will need this class: HZip.php and downloadall.php. In the code, change the name of the images folder to profilepics. If permissions are set up correctly, then the following HTML will download a zip file:
        download all html

    Assessment:

    It must meet all the criteria listed above.

    To hand in:

    It will be assessed in class.

    If you plan on writing a log in system, your site needs to be able to remember if the user is logged in. This can be achieved using PHP sessions.

    Learn about PHP Sessions:
    1. Read this tutorial: w3 PHP Sessions
    2. This code is demonstrated in Ms. Wear's Sessions Demo
    Hints to logging in
    1. To use sesssions, add session_start() to the top of each php file that serves content for your site.
    2. If a user is not logged in, set $_SESSION<'isLoggedIn'> to false and show the log in page. Use $_SESSION<'isLoggedIn'> to determine the status of a user. If a user is not logged in and tries to access a page that requires logging in, they should be forwarded to the log in page.
    Overview

    Turn TutorMD into a Platform for Mount Doug students to find tutors and to offer tutoring services.

    Read Best Practices for Working with Multiple Programmers and Password Encryption At Client Side

    Detailed Description

    1) User Interface - The user interface will:

    • include a gallery of tutors that shows thumbnails of all the profiles with each person's name displayed under their profile image and additional info as deemed appropriate.
    • be responsive, this means it looks good and is usable on a laptop or a mobile device. In order to do this, learn about responsive design:
      1. Read Learning the Basics of Web Design
      2. Watch Layout and Composition
      3. To learn about Responsive Design, read Responsive Web Design - Introduction
      4. To save yourself a lot of time, I suggest you use one of the bottom two responsive templates from w3 at CSS Layout Templates
    • have easy to use techniques for the user to accomplish all the functionality from parts 1-5 that are required to complete your unique site.
    • use an attractive design that follows the principles of design. Read 9 Principles of Good Web Design

    2) Your code will have the following qualities:

    • php and javascript commented/organized/formatted/designed in an efficient and easy to understand fashion
    • include a readme.txt file with a list and description of ALL files AND a link to your homepage
    • css and html are valid

    3) Basic Functionality

    • It has all the functionality up to and including that of TutorMD 5. Functionality from these assignments can be modified or changed to meet the needs of your unique site. It works. It is robust. It is reliable. It works. Did I mention, it works?

    4) Add the Following Required Functionality to TutorMD

    1. Add a Search box: Include a search box that will display all profiles found with the search terms in the name, description, grade, or tutorable subjects.
    2. Subjects Filter: In home include a collapsible menu of all subjects in a form that multiple subjects can be selected, then display only the thumbnails of tutors who can tutor the selected subjects.
    3. Grades Filter: In home include method to select one grade, then display only the thumbnails of tutors who are in that grade.
    4. Lightbox Functionality:
      • include "prev" and "next" buttons so the users can browse through the profiles in order they are displayed in the home page. Only images currently displayed should load in the lightbox.
      • Note: If you haven't already, you will want to use fetch data to load the name/description/tags into the lightboxes (instead of PHP) in this version.

    It works. It is robust. It is reliable. It works. Did I mention, it works?

    5) Make it even better:

    • Be creative. Figure out what the actual Peer Tutoring program really needs. Is it a login system? A tutor request system? A schedule? A better user interface than the one described in this assignment. Make this project good enough to function in the real world.

    It works. It is robust. It is reliable. It works. Did I mention, it works?

    Due Dates
    1. Milestone 1 (due two days after the project starts): A version of TutorMD 5 is up on the server on the team account. Each healthy person on the team has made at least one change to the code.
    2. Milestone 2 about 1 week later: Complete the "Grades" filter and finish your responsive CSS (layout should resize for wide screen vs phone).
    3. Milestone 3 tba: Complete the "All Subjects" filter and finish your main CSS look and feel.
    4. Final Deadline < 1 week later
    How to Hand in
    1. Submit a link to Google Classroom
    2. Hand in zip file of your entire project folder to Wear_IT > Hand-in > CompSci 12 > PHP Project
    3. For testing purposes, upload:
      1. at least 16 Tutor Profiles
      2. at least 16 examples of each additional each unique added feature like posts, chats, comments, likes, or anything else you invented that requires users to contribute content.
      3. Each unique thing should have valid content (names, description, etc). "asdf" and "jkl;" do not count as valid names or words.
      4. Ensure there is a variety of content. Don't use the same names, descriptions, and courses I tutor over and over.
      5. Add enough content that I can easily test and see all added functionality.
      6. Add enough options that there are multiple searches that return more than one result for names and subjects tutored.
    4. In the Google Classroom assignment document:
      1. Declare all functionality added beyond tutorMD 5.
      2. If you have a search function, declare at least 3 searches that will produce MULTIPLE results with the data you've entered.
      3. Declare all known bugs. No software is written without known bugs.
    Marking Criteria (/100): CS 12 Web Dev Project Rubric

    Example from a previous project:
    Rameta
    Rameta Rameta Rameta
    3 PHP WRITTEN programming and HTML problems. Open Everything. NCWAHBWICA. Linux Server will be OFFLINE. Date posted on Classroom.