Reusing PHP Code and Writing Functions…

Reusing Code and Writing Functions

In this lesson of the PHP tutorial, you will learn… 

  1. To write reusable files and include them in multiple pages.
  2. To write user-defined functions.
  3. To create a library of user-defined form-validation and form-entry functions.

Writing reusable code results in time and money savings, more consistent and bug free code, and the ability to hide complex code from less seasoned developers.

Including Files

PHP provides two common constructs for including files in web pages: require and include. They are basically the same with one minor difference. require throws a fatal error when it fails; whereas, include only gives a warning. If you need the included file to continue to process the page, you should use require.

It is important to keep in mind that a PHP tag cannot start in a calling file and continue in an included file. All PHP code in the included file must be nested in PHP tags.

require

require is not actually a function, but a language construct, so require statements can be written in two ways:

Syntax
require(path_to_file);

require path_to_file;

path_to_file can be an absolute or a relative path.

require_once

require_once can be used just like require. The difference is that if the included file has already been included by earlier code, it will not be re-included.

A Note on Security

If included files are under the web root, they can be accessed just as any other file can. If they have an extension such as inc then the browser may display them as plain text. With other extensions, the browser may attempt to download the file. If the included file is a PHP file and a user navigates to it, the server will try to process the file and may return errors. As a precaution, you may want to place your included files in a directory above or outside of the web root. This will prevent users from accessing the files directly.

include_path directive

The php.ini contains an include_path directive, which takes a semi-colon delimited list of paths to directories that PHP should look in for included files.

Here is a code sample that demonstrates how to include files using require.

Code Sample: ReusingCode/Demos/Require.php

<html>
<head>
<title>Including Files</title>
</head>
<body>
This text is on the main page.
<hr/>
<?php
 require 'Includes/Required.php';
?>
<hr/>
<?php
 require 'Includes/Required.inc';
?>
</body>
</html>
Code Explanation

The above code is relatively straightforward. Require.php contains two included (required) files: Required.php and Required.inc. Notice that there is PHP code inside of Required.inc, which is executed. The extension of the included files does not affect how the code inside the files will be executed.

Exercise: Adding a Header and Footer

Duration: 5 to 10 minutes.

In this exercise, you will add a header and a footer to a simple home page, which currently just contains a login form.

  1. Open Includes/Header.php and Includes/Footer.php in your editor and review the code.
  2. Open ReusingCode/Exercises/index.php in your editor.
  3. Add code to include Includes/Header.php and Includes/Footer.php at the top and bottom or the page.
  4. To test your solution, load ReusingCode/Exercises/index.php in the browser. It should display as follows:

auto_prepend_file and auto_append_file

The configuration file, php.ini, contains settings for automatically prepending and appending files to every PHP script. These settings are auto_prepend_file and auto_append_file. By default, they contain no values; however, they can be set to point to a files using absolute paths as follows:

; Automatically add files before or after any PHP document.
auto_prepend_file = "c:/inetput/include/runbefore.inc"
auto_append_file = "c:/inetput/include/runafter.inc"

The auto_prepend_file directive can be used to application-wide variables such as database connection strings or common file paths. The auto_append_file directive can be used for cleaning up code or for outputting debugging information to the browser.

Note that it is not possible to set different auto-prepend and auto-append files for different directories or different scripts.

User Functions

User functions are used to make common tasks easier and to make code more modular and easier to read. Unlike other identifiers in PHP, functions are case insensitive.

Defining and Calling Functions

A simple function is defined as follows.

Syntax
function myfunct()
{
 do this;
 do that;
 do this other thing;
}

Like built-in functions, user functions can receive parameters. To define a function with parameters, place receiving variables in the parentheses.

Syntax
function addNums($param1, $param2, $param3)
{
 $sum = $param1 + $param2 + $param3;
 echo 'The sum is ' . $sum;
}

User functions can also return values.

Syntax
function addNums($param1, $param2, $param3)
{
 $sum = $param1 + $param2 + $param3;
 return $sum;
}

User functions are called in the same way that built-in functions are. For example, the following code calls the addNums() function to get the sum of three numbers.

Syntax
$total = addNums(1,3,5);

See ReusingCode/Demos/SimpleUDF.php to see the above code in action.

Default Values

You can make function parameters optional by assigning default values to them as shown in the example below.

Code Sample: ReusingCode/Demos/DefaultValues.php

<html>
<head>
<title>Simple User-defined Function</title>
</head>

<body>
<?php
function addNums($param1=0, $param2=0, $param3=0)
{
 $sum = $param1 + $param2 + $param3;
 return $sum;
}

$Total = addNums(1,3);

echo $Total;
?>
</body>
</html>
Code Explanation

In this case, if you don’t pass a value into the function for one or more of the parameters, the default value of 0 will be used. When defining a function, all required parameters should precede optional parameters.

Variable Scope

In PHP, variables declared outside of functions are not available by default inside of functions. The following code illustrates this:

Code Sample: ReusingCode/Demos/LocalVars.php

<html>
<head>
<title>Local Variables</title>
</head>

<body>
<?php
$a = 10;
$b = 5;

function incrNumBy()
{
 $a += $b;
}
incrNumBy(); //results in two warnings as $a and $b are
     //undefined in the function scope
echo $a; //outputs 10 to the browser
?>
</body>
</html>

To make the variables available to the function, they must be declared within the function as global variables using the global keyword.

Code Sample: ReusingCode/Demos/GlobalVars.php

<html>
<head>
<title>Global Variables</title>
</head>

<body>
<?php
$a = 10;
$b = 5;

function incrNumBy()
{
 global $a,$b;
 $a += $b;
}
incrNumBy();
echo $a; //outputs 15 to the browser
?>
</body>
</html>

By Reference vs. By Value

By default, variables are passed to functions by value, meaning that the function’s receiving variables get copies of the values received rather than pointers to them. If the receiving variables are modified, the passed variables remain unaffected. The following code illustrates this.

Code Sample: ReusingCode/Demos/ByValue.php

<html>
<head>
<title>By Value</title>
</head>
<body>
<?php
 $a = 10;
 $b = 5;
 function incrNumBy($num,$incr)
 {
  $num += $incr;
 }

 incrNumBy($a,$b);
 echo $a; //outputs 10 to the browser
?>
</body>
</html>

The above code outputs “10” to the browser. Although $num was incremented by 5, $a was unaffected by the function call. To pass a variable by reference, put an ampersand (&) before the parameter in the function definition.

Code Sample: ReusingCode/Demos/ByReference.php

<html>
<head>
<title>By Reference</title>
</head>
<body>
<?php
 $a = 10;
 $b = 5;
 function incrNumBy(&$num,$incr)
 {
  $num += $incr;
 }

 incrNumBy($a,$b);
 echo $a; //outputs 15 to the browser
?>
</body>
</html>

This time the function outputs “15” because $num references the variable $a itself. So, any change in $num will affect $a.

Form Processing

Processing forms generally involves the following tasks:

  1. Writing the HTML code to output the form.
  2. Writing validation code to validate the form entries after the form is submitted.
  3. Writing code to output errors if there are any.
  4. Writing code to process the form entries if they are all valid.

Although these tasks are all separate, some are dependent on others. For example, if errors are found when the form is submitted, it is nice to re-output the form, but the HTML code may be different from the original form as you will likely want to include error messages and also echo the values that the user entered. It’s very easy to get your code all tangled up resulting in what is known as spaghetti code. We will now examine one approach for organizing code using functions and includes to make it easier to maintain.

Code Organization

Application Flow

The application we are building works like this:

  1. When the user first visits, she is presented with a form to fill out.
  2. If she fills out the form…
    • Correctly
      • She is presented with another form to confirm her entries.
      • After confirming her entries, the data will be processed (e.g, entered into a database or emailed to someone).
    • Incorrectly
      • She is presented with the same form with her entries in tact and appropriate error messages displayed.

Application Files

To make our code easier to maintain, we will organize it as follows:

  1. Includes/init.php – Initializes and sets some variables.
  2. AddEmployee.php – Contains code that defines the flow of the application.
  3. Includes/EmployeeForm.php – Contains code to display entry form.
  4. Includes/ProcessEmployee.php – Contains code to process the original form entry. If there are errors, they will be displayed on the page. If there are no errors, the user’s entries will be displayed with a “Confirm” button.
  5. Includes/InsertEmployee.php – Contains code to insert the employee into a database. (This file is currently empty.)
  6. Includes/fnFormPresentation.php – Contains a library of functions for presenting form fields.
  7. Includes/fnFormValidation.php – Contains a library of functions for validating form entries.
  8. Includes/fnStrings.php – Contains a couple of useful string functions.
  9. Includes/fnDates.php – Contains a useful date function.

We will examine each of these files.

Code Sample: ReusingCode/Demos/Includes/init.php

<?php
 $ShowForm = true;

 $MgrEntries = array();
 $MgrEntries[1]='Nancy Davolio';
 $MgrEntries[2]='Andrew Fuller';
 $MgrEntries[3]='Janet Leverling';
 $MgrEntries[4]='Margaret Peacock';
 $MgrEntries[5]='Steven Buchanan';
 $MgrEntries[6]='Michael Suyama';
 $MgrEntries[7]='Robert King';
 $MgrEntries[8]='Laura Callahan';
 $MgrEntries[9]='Anne Dodsworth';

 $Errors = array();
 $DbEntries = array( 'FirstName'=>'',
      'LastName'=>'',
      'Email'=>'',
      'Title'=>'',
      'TitleOfCourtesy'=>'',
      'Address'=>'',
      'City'=>'',
      'Region'=>'',
      'PostalCode'=>'',
      'Country'=>'',
      'HomePhone'=>'',
      'Extension'=>'',
      'Notes'=>'',
      'ReportsTo'=>'',
      'Password'=>'',
      'Email'=>'',
      'BirthMonth'=>1,
      'BirthDay'=>1,
      'BirthYear'=>date('Y'),
      'HireMonth'=>1,
      'HireDay'=>1,
      'HireYear'=>date('Y'));
 $BrowserEntries = array();
?>
Code Explanation

This file sets several variables used throughout the application.

Code Sample: ReusingCode/Demos/AddEmployee.php

<?php
 require 'Includes/fnFormValidation.php';
 require 'Includes/fnFormPresentation.php';
 require 'Includes/fnStrings.php';
 require 'Includes/fnDates.php';
 require 'Includes/init.php';
?>
<html>
<head>
<title>Add Employee</title>
<style type="text/css">
 .Error {color:red; font-size:smaller;}
</style>
</head>
<body>
<?php
 require 'Includes/Header.php';

 if (array_key_exists('Submitted',$_POST))
 {
  require 'Includes/ProcessEmployee.php';
 }
 elseif (array_key_exists('Confirmed',$_POST))
 {
  require 'Includes/InsertEmployee.php';
 }

 if ($ShowForm)
 {
  require 'Includes/EmployeeForm.php';
 }

 require 'Includes/Footer.php';
?>
</body>
</html>
Code Explanation

The code is relatively easy to read. Things to note:

  1. At the very top, we include several files we will need for the application.
  2. In the body, we include:
    • our header and footer files.
    • code that checks which, if either, form was submitted and includes the appropriate file.
    • code that checks whether or not to show the main form. The form will be shown if:
      • it has not yet been submitted.
      • it has been submitted with errors.

Code Sample: ReusingCode/Demos/Includes/fnDates.php

<?php
/********* DATE FUNCTIONS *********/

/*
 Function Name: monthAsString
 Arguments: $m
 Returns:
  month as string
*/
function monthAsString($m)
{
 $Months = array();
 $Months[] = 'January';
 $Months[] = 'February';
 $Months[] = 'March';
 $Months[] = 'April';
 $Months[] = 'May';
 $Months[] = 'June';
 $Months[] = 'July';
 $Months[] = 'August';
 $Months[] = 'September';
 $Months[] = 'October';
 $Months[] = 'November';
 $Months[] = 'December';

 return $Months[$m-1];
}
?>
Code Explanation

This file includes a simple function for getting the name of a month (e.g, February) given the month number (e.g, 2).

Code Sample: ReusingCode/Demos/Includes/fnStrings.php

<?php
/********** STRING FUNCTIONS *********/
/*
 Function Name: browserString
 Arguments: $String
 Returns:
  trimmed and escaped string for browser output
*/
function browserString($String)
{
 return nl2br(trim(htmlentities($String)));
}

/*
 Function Name: dbString
 Arguments: $String
 Returns:
  trimmed and escaped string for database entry
*/
function dbString($Email)
{
 if (get_magic_quotes_gpc())
 {
  return trim ($Email);
 }
 else
 {
  return addslashes(trim($Email));
 }
}

?>
Code Explanation

This file includes functions for cleaning up strings for browser and database output.

Code Sample: ReusingCode/Demos/Includes/fnFormPresentation.php

<?php
/********* FORM PRESENTATION FUNCTIONS *********/

/*
 Function Name: textEntry
 Arguments: $Display,$Name,$Entries,$Errors,$Size?
 Returns:
  one table row as string
*/
function textEntry($Display,$Name,$Entries,$Errors,$Size=15)
{
 $ReturnVal = "
 <tr>
  <td>$Display:</td>
  <td>
   <input type='text' name='$Name' size='$Size'
   value=\"" . browserString($Entries[$Name]) . "\">";

 if (array_key_exists($Name,$Errors))
 {
  $ReturnVal .= '<span style="white-space:nowrap">* ' .
    $Errors[$Name] .
   '</span>';
 }

 $ReturnVal .= "</td>
 </tr>";

 return $ReturnVal;
}

/*
 Function Name: pwEntry
 Arguments: $PW1,$PW2,$Errors,$Size?
 Returns:
  table rows as string
*/
function pwEntry($PW1,$PW2,$Errors,$Size=10)
{
 $ReturnVal = "
 <tr>
  <td>Password:</td>
  <td>
   <input type='password' name='$PW1' size='$Size'>
  </td>
 </tr>
 <tr>
  <td>Repeat Password:</td>
  <td>
   <input type='password' name='$PW2' size='$Size'>
  </td>
 </tr>";

 if (array_key_exists('Password',$Errors))
 {
  $ReturnVal .= addErrorRow('Password',$Errors);
 }
 return $ReturnVal;
}

/*
 Function Name: textAreaEntry
 Arguments: $Display,$Name,$Entries,$Errors,$Cols?,$Rows?
 Returns:
  table rows as string
*/
function textAreaEntry($Display,$Name,$Entries,$Errors,$Cols=45,$Rows=5)
{
 $ReturnVal = "
 <tr>
  <td colspan='2'>$Display:</td>
 </tr>
 <tr>
  <td colspan='2'>
   <textarea name='$Name' cols='$Cols' rows='$Rows'>";
   $ReturnVal .= $Entries[$Name];
   $ReturnVal .= "</textarea>
  </td>
 </tr>";

 if (array_key_exists($Name,$Errors))
 {
  $ReturnVal .= addErrorRow($Name,$Errors);
 }
 return $ReturnVal;
}

/*
 Function Name: radioEntry
 Arguments: $Display,$Name,$Entries,$Errors,$Values
 Returns:
  table rows as string
*/
function radioEntry($Display,$Name,$Entries,$Errors,$Values)
{
 $ReturnVal = "
 <tr>
  <td>$Display:</td>
  <td>$Name</td>
 </tr>";

 return $ReturnVal;
}

/*
 Function Name: selectEntry
 Arguments: $Display,$Name,$Entries,$Errors,$Selected?
 Returns:
  table rows as string
*/
function selectEntry($Display,$Name,$Options,$Errors,$Selected=0)
{
 $ReturnVal = "<tr>
  <td>$Display:</td>
  <td>
   <select name='$Name'>
   <option value='0'>Choose one...</option>";
   $ReturnVal .= "</select>
  </td>
  </tr>";
 return $ReturnVal;
}

/*
 Function Name: selectDateEntry
 Arguments: $Display,$NamePre,$Month,$Day,$Year
 Returns:
  table rows as string
*/
function selectDateEntry($Display,$NamePre,$Month,$Day,$Year,$Errors)
{
 $ReturnVal = "<tr>
  <td>$Display:</td>
  <td>
   <select name='$NamePre" . "Month'>";
   for ($i=1; $i<=12; $i++)
   {
    if ($i == $Month)
    {
     $ReturnVal .= "<option value='$i' selected>";
    }
    else
    {
     $ReturnVal .= "<option value='$i'>";
    }
    $ReturnVal .= monthAsString($i) . '</option>';
   }
   $ReturnVal .= "</select>
   <select name='$NamePre" . "Day'>";
   for ($i=1; $i<=31; $i++)
   {
    if ($i == $Day)
    {
     $ReturnVal .= "<option value='$i' selected>";
    }
    else
    {
     $ReturnVal .= "<option value='$i'>";
    }
    $ReturnVal .= "$i</option>";
   }
   $ReturnVal .= "</select>
   <select name='$NamePre" . "Year'>";
   for ($i=date('Y'); $i>=1900; $i=$i-1)
   {
    if ($i == $Year)
    {
     $ReturnVal .= "<option value='$i' selected>";
    }
    else
    {
     $ReturnVal .= "<option value='$i'>$i</option>";
    }
    $ReturnVal .= "$i</option>";
   }
   $ReturnVal .= '</select>
  </td>
 </tr>';

 if (array_key_exists($NamePre . 'Date',$Errors))
 {
  $ReturnVal .= addErrorRow($NamePre . 'Date',$Errors);
 }
 return $ReturnVal;
}

/*
 Function Name: addErrorRow
 Arguments: $Name
 Returns:
  table row as string
*/
function addErrorRow($Name,$Errors)
{
 $ErrorRow = '<tr><td colspan="2">* ' .
     $Errors[$Name] .
    '</td></tr>';
 return $ErrorRow;
}
?>
Code Explanation

This file contains functions for presenting form entries. Several of these functions are complete, but there are a couple that need to be finished. This will be part of the next exercise.

Code Sample: ReusingCode/Demos/Includes/fnFormValidation.php

<?php
/********* FORM VALIDATION FUNCTIONS *********/

/*
 Function Name: checkLength
 Arguments: $Text,$Min?,$Max?,$Trim?
 Returns:
  false if $Text has fewer than $Min characters
  false if $Text has more than $Max characters
  true otherwise
*/
function checkLength($Text,$Min=1,$Max=10000,$Trim=true)
{
 if ($Trim)
 {
  $Text = trim($Text);
 }
 if (strlen($Text) < $Min || strlen($Text) > $Max)
 {
  return false;
 }
 return true;
}

/*
 Function Name: checkEmail
 Arguments: $Email
 Returns:
  false if $Email has fewer than 6 characters
  false if $Email does not contain @ symbol
  false if $Email does not contain a period (.)
  false if the last @ symbol comes after the last period (.)
  true otherwise
*/
function checkEmail($Email)
{
 return true;
}

/*
 Function Name: checkPassword
 Arguments: $PW1,$PW2
 Returns:
  false if $PW1 has fewer than 6 characters
  false if $PW1 has more than 12 characters
  false if $PW1 and $PW2 do not match
  true otherwise
*/
function checkPassword($PW1,$PW2)
{
 return true;
}
?>
Code Explanation

This file contains functions for validating form entries. One of these functions is complete, but there are a couple that need to be finished. This will also be part of the next exercise.

Code Sample: ReusingCode/Demos/Includes/EmployeeForm.php

<h1 align="center">Add Employee</h1>
<form method="post" action="AddEmployee.php">
<input type="hidden" name="Submitted" value="true">
<table align="center" border="1" width="500">
 <?php 
  echo textEntry('First name','FirstName',$DbEntries,$Errors,15);
  echo textEntry('Last name','LastName',$DbEntries,$Errors,15);
  echo textEntry('Email','Email',$DbEntries,$Errors,25);
  echo textEntry('Title','Title',$DbEntries,$Errors,30);
  echo radioEntry('Title of Courtesy','TitleOfCourtesy',
   $DbEntries,$Errors,
   array('Dr.','Mr.','Mrs.','Ms.'));
  echo selectDateEntry('Birth date','Birth',
       $DbEntries['BirthMonth'],
       $DbEntries['BirthDay'],
       $DbEntries['BirthYear'],
       $Errors);
  echo selectDateEntry('Hire date','Hire',
       $DbEntries['HireMonth'],
       $DbEntries['HireDay'],
       $DbEntries['HireYear'],
       $Errors);
  echo textEntry('Address','Address',$DbEntries,$Errors,50);
  echo textEntry('City','City',$DbEntries,$Errors,30);
  echo textEntry('Region','Region',$DbEntries,$Errors,2);
  echo textEntry('Postal Code','PostalCode',$DbEntries,$Errors,10);
  echo textEntry('Country','Country',$DbEntries,$Errors,5);
  echo textEntry('Home phone','HomePhone',$DbEntries,$Errors,15);
  echo textEntry('Extension','Extension',$DbEntries,$Errors,5);
  echo textAreaEntry('Notes','Notes',$DbEntries,$Errors,50,3);
  echo selectEntry('Manager','ReportsTo',$MgrEntries,
         $Errors,$DbEntries['ReportsTo']);
  echo pwEntry('Password1','Password2',$Errors,10);
 ?>
 <tr>
  <td colspan="2"><input type="submit" value="Add Employee"></td>
 </tr>
</table>
</form>
Code Explanation

This file creates the entry form. Notice that it creates entry rows through calls to functions in the fnFormPresentation.php file. This allows us to easily incorporate error handling and error messages into the form entries without making the HTML form itself difficult to maintain.

Code Sample: ReusingCode/Demos/Includes/ProcessEmployee.php

<?php
 $DbEntries['FirstName'] = dbString($_POST['FirstName']);
 $DbEntries['LastName'] = dbString($_POST['LastName']);
 $DbEntries['Title'] = ucwords(dbString($_POST['Title']));
 $DbEntries['Address'] = dbString($_POST['Address']);
 $DbEntries['City'] = dbString($_POST['City']);
 $DbEntries['Region'] = dbString($_POST['Region']);
 $DbEntries['PostalCode'] = dbString($_POST['PostalCode']);
 $DbEntries['Country'] = dbString($_POST['Country']);
 $DbEntries['HomePhone'] = dbString($_POST['HomePhone']);
 $DbEntries['Extension'] = dbString($_POST['Extension']);
 $DbEntries['Notes'] = dbString($_POST['Notes']);
 $DbEntries['ReportsTo'] = $_POST['ReportsTo'];
 $DbEntries['Password'] = dbString($_POST['Password1']);
 $DbEntries['Email'] = dbString($_POST['Email']);
 $DbEntries['BirthMonth'] = dbString($_POST['BirthMonth']);
 $DbEntries['BirthDay'] = dbString($_POST['BirthDay']);
 $DbEntries['BirthYear'] = dbString($_POST['BirthYear']);
 $DbEntries['HireMonth'] = dbString($_POST['HireMonth']);
 $DbEntries['HireDay'] = dbString($_POST['HireDay']);
 $DbEntries['HireYear'] = dbString($_POST['HireYear']);

 if (!checkLength($_POST['FirstName']))
 {
  $Errors['FirstName'] = 'First name omitted.';
 }
 else
 {
  $BrowserEntries['FirstName'] = browserString($_POST['FirstName']);
 }

 if (!checkLength($_POST['LastName']))
 {
  $Errors['LastName'] = 'Last name omitted.';
 }
 else
 {
  $BrowserEntries['LastName'] = browserString($_POST['LastName']);
 }

 if (!checkLength($_POST['Title']))
 {
  $Errors['Title'] = 'Title omitted.';
 }
 else
 {
  $BrowserEntries['Title'] = ucwords(browserString($_POST['Title']));
 }

 if ( array_key_exists('TitleOfCourtesy',$_POST) )
 {
  $BrowserEntries['TitleOfCourtesy'] = browserString($_POST['TitleOfCourtesy']);
  $DbEntries['TitleOfCourtesy'] = dbString($_POST['TitleOfCourtesy']);
 }
 else
 {
  $Errors['TitleOfCourtesy'] = 'Title of Courtesy not selected.';
 }

 if (!checkdate($_POST['BirthMonth'],$_POST['BirthDay'],$_POST['BirthYear']))
 {
  $Errors['BirthDate'] = 'Birth date is not a valid date.';
 }

 if (!checkdate($_POST['HireMonth'],$_POST['HireDay'],$_POST['HireYear']))
 {
  $Errors['HireDate'] = 'Hire date is not a valid date.';
 }

 if (!checkLength($_POST['Address'],5,200))
 {
  $Errors['Address'] = 'Address omitted.';
 }
 else
 {
  $BrowserEntries['Address'] = browserString($_POST['Address']);
 }

 if (!checkLength($_POST['City'],1,100))
 {
  $Errors['City'] = 'City omitted.';
 }
 else
 {
  $BrowserEntries['City'] = browserString($_POST['City']);
 }

 if (!checkLength($_POST['Region'],2,2) && !checkLength($_POST['Region'],0,0))
 {
  $Errors['Region'] = 'Region name must be two characters.';
 }
 else
 {
  $BrowserEntries['Region'] = browserString($_POST['Region']);
 }

 if (!checkLength($_POST['PostalCode']))
 {
  $Errors['PostalCode'] = 'Postal Code omitted.';
 }
 else
 {
  $BrowserEntries['PostalCode'] = browserString($_POST['PostalCode']);
 }

 if (!checkLength($_POST['Country']))
 {
  $Errors['Country'] = 'Country omitted.';
 }
 else
 {
  $BrowserEntries['Country'] = browserString($_POST['Country']);
 }

 if (!checkLength($_POST['HomePhone'],10,15))
 {
  $Errors['HomePhone'] = 'Home phone must be between 10 and 15 characters.';
 }
 else
 {
  $BrowserEntries['HomePhone'] = browserString($_POST['HomePhone']);
 }

 if (!checkLength($_POST['Extension'],3,5))
 {
  $Errors['Extension'] = 'Extension must be between 3 and 5 characters.';
 }
 else
 {
  $BrowserEntries['Extension'] = browserString($_POST['Extension']);
 }

 if (!checkLength($_POST['Notes'],0,100))
 {
  $Errors['Notes'] = 'Notes must be fewer than 100 characters:<br/>
   <span style="color:blue; font-weight:normal">' .
   browserString(substr($_POST['Notes'],0,100)) .
   '</span><span style="color:red; font-weight:normal;
   text-decoration:line-through;">' .
   browserString(substr($_POST['Notes'],100)) .
   '</span>';
 }
 else
 {
  $BrowserEntries['Notes'] = browserString($_POST['Notes']);
 }

 if ($_POST['ReportsTo'] == 0)
 {
  $Errors['ReportsTo'] = 'Manager not selected.';
 }
 else
 {
  $BrowserEntries['ReportsTo'] = $_POST['ReportsTo'];
 }

 if ( !checkPassword($_POST['Password1'],$_POST['Password2']) )
 {
  $Errors['Password'] = 'Passwords do not match or are not the right length.';
 }
 else
 {
  $BrowserEntries['Password'] = browserString($_POST['Password1']);
 }

 if ( !checkEmail($_POST['Email']) )
 {
  $Errors['Email'] = 'Email is invalid.';
 }
 else
 {
  $BrowserEntries['Email'] = browserString($_POST['Email']);
 }
?>
<?php
 if (!count($Errors))
 {
  $ShowForm = false;
?>
 <form method="post" action="AddEmployee.php">
 <input type="hidden" name="Confirmed" value="true">
 <?php
  echo '<h2>Confirm Entries</h2>';
  echo '<ol>';
  foreach ($BrowserEntries as $key=>$Entry)
  {
   if ($key=='ReportsTo')
   {
    echo "<li><b>Manager:</b> $MgrEntries[$Entry]</li>";
   }
   else
   {
    echo "<li><b>$key:</b> $Entry</li>";
   }
  }
  echo '</ol>';

  foreach ($DbEntries as $key=>$Entry)
  {
 ?>
  <input type="hidden" name="<?php echo $key ?>"
   value="<?php echo $Entry ?>">
 <?php
  }
 ?>
  <input type="submit" value="Confirm">
 </form>
<?php
 }
 else
 {
  $DbEntries = $_POST;
 }
?>
Code Explanation

This file contains code for processing the form entries. It makes use of functions in the fnFormValidation.php file for validating entries. If no errors are found, it sets the boolean $ShowForm to false, so that the original form will not be displayed and it outputs all the entries (made browser-safe) to the browser for confirmation. If errors are found, it adds them to the $Errors array, which is passed into the form presentation functions, so that they can return code for displaying the errors. If there are errors, the boolean $ShowForm is left as true, so that the original form is redisplayed.

Code Sample: ReusingCode/Demos/Includes/InsertEmployee.php

TO DO LATER
Code Explanation

This file will eventually contain code for inserting the employee information into the database.

Exercise: Form Validation and Presentation Functions

Duration: 45 to 60 minutes.

In this exercise, you will complete several functions needed for the application we have just seen.

  1. Open ReusingCode/Exercises/Includes/fnFormPresentation.php in your editor.
  2. Complete the radioEntry() and selectEntry() functions so that the return value contains correct form entries and, if appropriate, errors.
  3. Open ReusingCode/Exercises/Includes/fnFormValidation.php in your editor.
  4. Complete checkEmail() and checkPassword(), so that they return true if the form entry is valid and false otherwise.
  5. To test your solution, open ReusingCode/Exercises/AddEmployee.php in your browser and submit the form several times entering different data combinations each time.

Reusing Code and Writing Functions Conclusion

In this lesson of the PHP tutorial, you have learned to use includes and user functions to create more manageable PHP applications.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s