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.
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.
    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: "Name"
      • a file upload field labelled: "Profile Pic"
      • a checkbox labelled: "I give RamBook non-exclusive, transferable, sub-licensable, royalty-free, worldwide license to use this photo.
      • three radio buttons labelled: "Connection to Mount Doug:" with one radio button option as "Current Student", one option as "Alumni", and one option as "Staff"
      • If "Current Student" is checked in the radio buttons, use JavaScript to display a select element with grades 9-12 listed labelled: "Current Grade"
      • a textarea for a description about the user labelled: "Say Something About Yourself"
      • a submit button which submits the form using POST
    2. Validate your CSS and 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 rambook1.
    5. To hand in: Ms. Wear will check it in class.
    Modify Rambook 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 rambook2
    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

    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 form.inc. 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 test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
      }
      

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

    **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.

    
    
        {
            "name": "Suzy",
            "connection": "student",
            "grade": "11",
            "description": "Like to chill and hang with my gal pals, and love my little pony.",
            "permission": "t"
        },
        {
            "name": "Boyang",
            "connection": "alumni",
            "grade": "",
            "description": "Best year of my life. Loved Mr. Mclaren's Drafting class.",
            "permission": "t"
        },
        {
            "name": "Binita",
            "connection": "student",
            "grade": "12",
            "description": "Never got that rona and YEET it's my final year which it totally lit. ",
            "permission": "t"
        },
        {
            "name": "Darius",
            "connection": "alumni",
            "grade": "",
            "description": "Far out, so cool to find y'all do ya dig?",
            "permission": "t"
        }
    
    
    

    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

    // include functions.php if that's a thing
    // declare all variables
    // if the form was submitted, validate it
    // if the form was submitted successfully, write the data to the file
    // include the header, 
    // if the form was submitted with errors show form
    // else if the form was submitted successfully show home
    // else if one of the links was clicked show that page
    // else show home.inc...home.inc needs to open the file and read it
    // include  footer
    
    
    
    **bold indicates the minimum of what must be added to Rambook 2. You will also need to add conditional statements to remove warnings from PHP.

    What to do for this assignment:

    1. Add submitted form contents to the master data file called userprofiles.json in JSON format.
    2. 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.
    3. 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/rambook3.

    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 Image Gallery, 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){
          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. 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:
         {
            "name": "Darius",
            "connection": "alumni",
            "grade": "12",
            "description": "Far out, so cool to find y'all do ya dig?",
            "permission": "t"
            "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 rambook4
  • .

    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/rambook5/getData.php?uid=2
      
      should display the JSON for the element with the uid = 2.
    2. In 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/rambook5/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 of the RamBook, we are adding a number of improvements.

    Add the following functionality to RamBook:
    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. **I suggest using the code from CS 11.**
      • See the lesson below for more info.
      • Display the name of the user, their relationship to Mount Doug, their grade, and their description in the lightbox.
      • 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:
      • On the home page, include an "Add Profile" link or button which takes the user to the form.
      • To return from the form to the gallery, use the "View Profiles" link or button.
      • On the home page, include a "Reset Gallery" 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.
      • Add a Download All Button: Add a "download all" button on the homepage 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.

    For most of the functionality is part 6, you need to learn how to use JavaScript fetch to retrieve json data. This will enable your site to retrieve json data from the server without reloading the page. It is key for a seamless user interface experience.

    Get up to speed on some new code:
    1. Watch Fetching JSON data
    2. This is a video addressing an old project where images were classified as public or private. Now we have "staff/student/alumni". Watch Ms. Wear's Video Fetching JSON from a PHP Script. Download the code for it here: JSON.zip. Test this working example.
    3. Here is additional documentation on using fetch: Modern AJAX with Fetch API.
    4. Using the Fetch API to send and receive JSON with PHP.
    Add the Following Functionality to Rambook
    1. View Only Students/Alumni/Staff: In home include a method for selecting only "students" , "alumni", "staff", or all profiles and then display only those thumbnails.
    2. Lightbox Functionality:
      • include "prev" and "next" buttons so the users can browse through the profiles in order they are displayed in the gallery. Only images currently displayed should load in the lightbox.
      • Note: You will want to use fetch data to load the name/description/tags into the lightboxes (instead of PHP) in this version.
    3. Add a Search::
      • Include a search box that will display all profiles found with the search terms in the description or name.

    Assessment:

    It must meet all the criteria listed above.

    To hand in:

    Submit a link on Google Classroom.
    Overview

    Turn RamBook into a Social Media Platform for Mount Doug students and alumni. Beautify the front end of the site using responsive design and the principles of modern design.

    Detailed Description

    1) The Home Page - is a gallery of thumbnails of all the profiles with each person's name displayed under their profile image.

    2) User Interface - The user interface will:

    3) 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

    4) Basic and Extra Functionality

    • It has all the functionality up to and including that of Rambook 6. Extra Functionality is added functionalitythat contributes to the Social Media experience of the app.

    How to Hand in
    1. Submit a link to Google Classroom
    2. Hand in zip file of your entire project folder to Google Classroom
    3. For testing purposes, upload:
      1. at least 16 images
      2. Each of the above images should have valid names, description and tags. "asdf" does not count as valid.
      3. Ensure there are a variety of names, descriptions and tags. Do not use the same ones over and over.
      4. Add enough content that I can easily test and see all added functionality.
    Marking Criteria (/25)

    User Interface and Design (/5)

    • Meets all criteria listed above with reliability, robustness, and usability
    5 4 3 2 1
    all criteria fully met 1 criteria not fully met 2 criteria not fully met 3 criteria not fully met 4+ criteria not fully met

    Code (/5)

    • Meets all criteria listed above
    5 4 3 2 1
    all criteria fully met 1 criteria not fully met 2 criteria not fully met 3 criteria not fully met 4+ criteria not fully met

    Basic Functionality (/5)

    • Has all functionality up to and including Rambook 6 without bugs/errors/usability issues.
    5 4 3 2 1
    all criteria fully met 1 criteria not fully met 2 criteria not fully met 3 criteria not fully met 4+ criteria not fully met

    Added Functionality (/5)

    • Added functionality that adds to the Social Media experience of the app.
    5 4 3 2 1
    all criteria fully met 1 criteria not fully met 2 criteria not fully met 3 criteria not fully met 4+ criteria not fully met

    Handed in Correctly (/5)

    • Meets all criteria listed above
    5 4 3 2 1
    all criteria fully met 1 criteria not fully met 2 criteria not fully met 3 criteria not fully met 4+ criteria not fully met

    FAQ's
    1. When a user submit's a new image, what page should display after the form is submitted? It should confirm the successful upload and go to the home page.
    3 PHP programming problems. Date posted on Classroom.