Web Programming Languages

PHP Source Code: fwrite.php

<?php
//----------------------------------------------------------
//   The Web Language Project
//   Mark Brautigam
//   May-June 2015
//   http://www.mixed-up.com/markb/
//----------------------------------------------------------

include "common.php";
headers1();
headers2();
echo sidebar("php", "fwrite", "php");
?>
  
  <div id="content">
    <h2>PHP: Form Handling and Write to File</h2>

<?php
    
  draw_form ();

  if (isset ($_POST['submit']) && formHasData($_POST)) {
    draw_feedback ($_POST);

    // Append these values to the data file as one line
    // with the values separated by vertical bars: |
    //
    $fp = fopen ("../data/courses.txt", "a");
    fwrite ($fp, "{$_POST['college']}|{$_POST['dept']}|{$_POST['course']}|{$_POST['desc']}\n");
    fclose ($fp);
  }
?>
    <p><a href='fread.php'>Show the contents of this file »</a></p>
    <p><a href='source.php?f=3'>Show PHP source code »</a>
  </div>

<?php 
  footers(); 

  //-------------------------------------------------------------
  function draw_feedback ($post)
  //-------------------------------------------------------------
  {
    // Draw the HTML table that shows what values they wrote
    //
    echo "<p>The following data was entered in the data file: </p>\n";
    echo "<table class='results'>\n";
    echo "  <tr><td>College:</td><td>{$post['college']}</td></tr>\n";
    echo "  <tr><td>Department:</td><td>{$post['dept']}</td></tr>\n";
    echo "  <tr><td>Course #:</td><td>{$post['course']}</td></tr>\n";
    echo "  <tr><td>Course name:</td><td>{$post['desc']}</td></tr>\n";
    echo "</table>\n";
  }

  //-------------------------------------------------------------
  function formHasData ($p)
  //-------------------------------------------------------------
  {
    $formFields = array ( 'college', 'dept', 'course', 'desc' );
    for ($i=0, $n=count($formFields); $i<$n; $i++) {
      if (isset($p[$formFields[$i]]) && trim($p[$formFields[$i]]) != "")
        return true;
    }
    return false;
  }

  //-------------------------------------------------------------
  function draw_form ()
  //-------------------------------------------------------------
  { ?>
  <form name='coursesform' action='fwrite.php' method='POST'>
    <fieldset>
    <legend>Add a course</legend>
    <table>
      <tr><td>College:</td><td><input type='text' name='college' /></td></tr>
      <tr><td>Department:</td><td><input type='text' name='dept' /></td></tr>
      <tr><td>Course #:</td><td><input type='text' name='course' /></td></tr>
      <tr><td>Course name:</td><td><input type='text' name='desc' /></td></tr>
      <tr><td></td><td><input type='submit' id='submit' name='submit' value='Add' /></td></tr>
    </table>
    </fieldset>
  </form>
  <?php
  }
?>