Title: Competency 4.1, 2402--Intermediate Web Programming
Course: Intermediate Web Programming (25436)

ITSE 2402 Intermediate Web
PHP Module 4.1 Assignment

Assignment

1. Our class server does not allow you to create a file through coding (This is a security measure.) Therefore, you will need to hand create your text file first, then you can add to and change the file.
2. Even though the php practice pages mentioned in the optional reading is not graded, it is recommend that everyone work with those files so that you are more successful using PHP to read and write to files.
3. You will build on your ATM project. In competency 3, you created links to pages that are to be written using PHP.
4. First you are to use your text editor to create, save, and upload a file.
  - Open your editor.
Enter 1000.00.
Save the file as balance.txt in the module4 folder.
  - Using Filezilla, upload balance.txt to the module4 folder.
  - After uploading, while you are still in Filezilla
    - Right click on the balance.txt file.
    - Click on File Permissions.
    - Click on each check box in the Read and Write columns or simply enter 666 in the permission code box.
    - After selecting the check boxes, or entering the permission code, you should see 666 in the permission code text box.
    - Click OK. (If you use another file transfer program your goal is to end up with "chmod 666 for your balance.txt"
    - Every time you reupload this file, you may need to go back and set the permission code.
5. Second you are to create a program that contains a function to read the value in your balance.txt file. This is an external function because we can call it from several different pages.
  - Create a getBalance.php page.

    -                         <?php
                        function readBalance()
                        { $file = "balance.txt";
                        $fp = fopen($file, "r");
                        if (!$fp)
                        {
                        echo "<p>Could not open the data file.</p>";
                        $balance = 0;
                        }
                        else
                        {
                        $balance = fgets($fp);
                        fclose ($fp);
                        }
                        return $balance;
                        }
                        ?>

    - Look at the code. All statements are contained in the function readBalance()
    - The statement
$file = "balance.txt";
means that the file name balance.txt is assigned to the variable handle $file.
    - When you work with a file you must open a file before you use it and close it when you are done.
* The statement
$fp = fopen($file, "r");
means that the variable $fp is assigned the value returned from the function fopen($file, "r");
* The function fopen opens the file represented by the variable handle $file (in this case balance.txt). The "r" means that the file is opened for read-only
    - The if statement checks to see if the file did not open successfully.
* If the file did not open successfully the message "Could not open the data file" is displayed and the variable $balance is assigned the value 0.
* If the file did open successfully, the variable $balance is assigned the value returned from the function fgets for the file just opened.
* The call to the function fclose closes the file.
    - The return statement returns the variable $balance.
6. Third, create a testBalance.php page that calls a php file to read the balance.
  - Open your template.htm.
  - Save as testBalance.php
  - Enter the following code into the body of the page.

  -                   <h1>Testing Account Balance</h1>
                  <?php
                  include 'getBalance.php';
                  $returnValue = readBalance();
                  echo "<p>Account balance: " ;
                  printf ( "%01.2f", $returnValue ) ;
                  echo "</p>" ;
                  ?>

  - Look at the php code in the page.
  - The include statement says to include the file getBalance.php.
  - The statement
$returnValue = readBalance();
means that the value returned from the function readBalance (in the getBalance.php file) is assigned to the variable $returnValue.
  - The echo statement displays "Account balance: "
  - The printf statement formats the variable $returnValue to show 2 decimal places and displays that value to the screen.
  - The echo statement closes the p tag so that the page will validate once it is rendered.
7. Test your pages
  - Either upload your pages to your module4 folder on your site (and update your index page) or test your pages locally. You do not set your permissions when working in localhost.
  - Your balance.txt file must be in the same folder as your getBalance.php page or you will have to change your path when opening your file.
  - Your should be able to click on your balance button and read the balance of your account.
8. Practice Writing to a File
  - Making a deposit that updates your balance in your balance.txt file
    - testDeposit.php
      - Open your templateHTML5.htm page
      - Save as testDeposit.php
      - Add the following code to the body

                        <?php
                        include 'getBalance.php';
                        $returnValue = readBalance();
                        echo "<p>Starting balance: " ;
                        printf ( "%01.2f", $returnValue ) ;
                        echo "</p>" ;
                        ?>
                        <h1>Testing Deposit Page</h1>
                        <form  method="post"
                        action="addBalance.php" enctype="application/x-www-form-urlencoded">
                        <p>deposit amount:<input type="text" name= "depositAmount" id="depositAmount" /></p>
                        <p><input type="submit" id="makeDeposit" value="Make Deposit" /></p>
                        </form>

      - Look at the code.
      - The php coding to show the starting balance is the same as the coding used in testBalance.php.
      - The form tag shows that the action transfers the page to addBalance.php.
      - There is a text box to obtain a deposit amount.
  - Sending Form Data to a PHP page
    - Handling Form Submission
      - The data that a PHP script receives from a form submission usually takes the form of a text string assigned to the $_GET and $_POST autoglobals.
      - The built-in $_GET function is used to collect values from a form sent with method="get".
      - The built-in $_POST function is used to collect values from a form sent with method="post".
      - When using method="get" in HTML forms, all variable names and values are displayed in the URL.
      - When using method="post" in HTML forms, all variable names and values are hidden.
      - $_GET has a 100 character limit on the amount of information sent.
      - $_POST has an 8MB limit that can be overridden by changing the post_max_size in the php.ini file.
      - Except for the size and visibility, you use them the same.
      - You don't have to parse the string. You can find the value simply by referring to the name of the element of the form.
      - Since php is loosely typed, using implicit typing (float) will force the value to be a numeric float value instead of a string.
    - Creating an addBalance.php page to update your balance.txt file

                  <?php
                  $newDeposit=(float)$_POST['depositAmount'];
                  $file = "balance.txt";
                  $fp = fopen($file, "r");
                  if (!$fp)
                  {
                    echo "<p>Could not open the data file.<br />";
                    echo "The system is down.  Please try back later.</p>";
                    echo "<p><a href=\"login.php\">Login Page</a></p>";
                    exit;
                  }
                  else
                  {
                    $balance = fgets($fp);
                  }
                  fclose ($fp);

                  $file = "balance.txt";
                  $fp = fopen($file, "w+");
                  if (!$fp)
                  {
                    echo "<p>Could not open the data file.</p>";
                    echo "The system is down.  Please try back later.";
                    echo "<p><a href=\"login.php\">Login Page</a></p>";
                    exit;
                  }
                  else
                  {
                    $newBalance = $balance + $newDeposit;
                    fwrite( $fp, "$newBalance");
                  }
                  fclose ($fp);
                  echo "Thank you for your deposit.<br />For another transaction return to the login page.";
                  echo "<p><a href=\"login.php\">Login Page</a></p>";
                  ?>

    - $_GET and $_POST variables are used in PHP to retrieve information from forms, like user input. In the first statement $_POST looks for the value associated with the name depositAmount and assigns that value to the variable $newDeposit.
    - This coding is similar to the coding in getbalance.php; however, there are a few differences.
      - When the file does not open:
        - a message is sent "Could not open the data file"
        - a message is sent to the user that "The system is down. Please try back later." (If your properties of your balance.txt are not set properly, you will see this message.)
        - a link back to the login page is provided.
        - the code is exited so that the rest of the code cannot be invoked.
      - When the file opens,
        - the value written to the file is read by the fgets() function and that value is assigned to the variable $balance.
    - The file is again closed.
      - You had to close the file because you want to write back to the file.
    - Open the file again, but this time using a w+ so that you can overwrite the old data with the new data.
    - Again you test to see if the file was not opened, display appropriate messages, and exit if it did not.
    - When the file opens correctly:
      - assign the variable $newBalance to be the value of $newDeposit added to $balance.
      - write out the $newBalance to the file (this is an overwrite).
    - Close the file
    - Display messages to the screen.
    - Add a link to allow the user to return to the Login Page.
    - Test your pages by either upload or in localhost.
9. Withdrawal Page
  - Write a php page for your withdrawal page.
    - When you open a file to write, it is the same as starting a new file. You are expected to put a new value in. If there is not enough money in the account, you do not want to open the file.
    - Follow the same code as you did for the deposit example for reading the balance:
      - Open your file to read
      - Read your balance and assign that value to a variable
      - Closing the file
    - Test that there are sufficient funds before you open the file to write; otherwise, you will lose all information on the balance.txt file when you close it.
    - When there are insufficient funds, display a message to the user and exit.
    - When there are sufficient funds, subtract the withdrawal from the balance and write the new balance to the balance file.
10. You are going to update your ATM program to create another file, transaction.txt. The transaction.txt file will keep track of each transaction made by type d for deposit and w for withdrawal, the amount of the transaction, and the balance after the transaction is complete.
  1. The transaction.txt file is a data file with both a string value and two amounts.

                    d 500.00 1500.00
                    w 100.00 1400.00

11. Creating transaction pages
The following PHP function transValues.php reads the transaction.txt file when called:

              <?php
              function readTrans()
              { $file = "transaction.txt";
                $fp = fopen($file, "r");
                if (!$fp)
                {
                  echo "<p>Could not open the transaction file.</p>";
                }
                else
                {
                  $transData = fgets($fp);
                  while (!feof ($fp))
                  {
                    $transArry = explode(" ", $transData);
                    $type = $transArry[0];
                    $amount = $transArry[1];
                    $balance = $transArry[2];
                    if ($type == 'w')
                      echo "<p>withdrawal ".$amount." ".$balance." </p>";
                    else
                      echo "<p>deposit ".$amount." ".$balance." </p>";
                    $transData = fgets($fp);
                  }
                  fclose($fp);
                }
              }
              ?>

12. Look at the code.
  1. If the file opens, a priming read is used. The fgets gets a line from an open file and places it in the variable $transData.
  2. The while loop begins to see if the end of file was read (rather than a transaction).
    - Break the string $transData using explode() function into an array $transArry.
    - The first value $transArry[0] is then read into the variable $type.
    - The second value is read into the variable $amount.
    - The third value is read into the variable $balance.
    - A message is displayed based on the type of transaction.
    - The variable $type is tested to see if it is a 'w'.
    - Either the label withdrawal or deposit is entered as a label to the variables $amount and $balance.
    - The next value in the file is read into the variable $trans.
    - The while loop ends
  3. The file is closed.
13. If you want to add data to a file that already has data, then it must be opened in the append mode. The write mode, overwrites from the beginning of the file. The append, adds the next value after the last value in the file.
14. If you want to write more than one variable to a file, be sure to separate the variables with a space so that there will be a space in the file. For instance the statement
fwrite( $fp, "$transType $newTrans $balance\n");
will write to the file $fp the variable $transType, a space, the variable $newTrans, a space, the variable $balance, and an end of line.
15. Create a new blank text file called transaction.txt and upload to your site.
16. Make sure the properties have the value 666 so that you can write to the file.
17. Continue working with your ATM/money conversion problem.
18. You will need a new button on your login page to "List Transactions".
19. On both of your deposit and withdrawal pages, add the ability to write the type of transaction being made and the amount of the transaction to your transaction.txt file.
20. Create a new page that will list all transactions made.

Update your index page:

- Add links on your index page to the pages in your assignment folder that are to be graded:
- Remember to change your links to match the names of your pages if necessary so that your pages will link to each other
- Remember to use your validation icons to aid in my grading.

Uploading:

- Upload your revised index.htm page to the public_html folder.
- Upload your module4 folder with the files needed to display your work.

Testing uploaded pages

- Once uploaded, go to your site
- Validate your index page and all pages in this assignment (your css page will validate through the html pages that refer to your css page)
- Make any corrections for any page that does not validate or display correctly.
- Email your instructor for grading.