PHP DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


Phorm Manager
Pages: 1, 2, 3

Program flow

The design of a good program involves breaking the task's specification into smaller and smaller logical parts. Computer science theorists like to call this process decomposition or partitioning. When the parts cannot be broken into smaller logical pieces, you have a blueprint for a coding solution. In essence:



Sub_Program_One();
Sub_Program_Two();

Sub_Program_N();

Walk through the logic step by step. When you can say if Sub_Program_One does its job and Sub_Program_Two does its job, and so on, the logic is completed. When all the individual subprograms are successfully coded and tested, the job is done. The top of your program should, to a practical degree, be a logic road map with calls to subprograms and a minimal amount of individual executable statements. This technique avoids the "spaghetti code" characterizing so much poor programming. If you follow this paradigm, the Phanatic will be proud of you and the people (including you) who will modify your program in the future will be very grateful.

Good programing design and coding style transcend any specific language. Try and remember our goals: Effectiveness, Maintainability, and Efficiency.

The first series of the Phorm Manager's function calls are:

StartUp($SystemVariables,$Action);
GetFormData($Method, $FormVariables);
FixArrays($SystemVariables,$FormVariables,$LongestName);
MakeHTMLtop($HTML,$SystemVariables);
LegalDomain($HTML,$AcceptableDomains,$SystemVariables);

The application's first subprogram call is to StartUp(). This function loads the SystemVariables with allowable fields and, in some cases, default values. A few lines are:

$SystemVariables = array(
    formaction=>"M",
    allownamealias=>True,  # Allow name aliasing
    recipient=>"",  # E-mail recipient - only required hidden field
    sendacknowledgement=>"",  # Send submitter an acknowledge
    subject=>"Form Submission",  # E-mail subject   

  # Cosmetic properties. The first six are for the <BODY> tag.
    bgcolor=>"WHITE",  # Background color
    linkcolor=>"BLUE",  # Link color
    vlinkcolor=>"RED",  # Visited link color
    textcolor=>"BLACK",  # Text Color
    alinkcolor=>"GREEN",  # Active Link Color
    background=>"",  # Background graphic

The $SystemVariables associate array defines all allowable "name" control and cosmetic properties. In addition, default values are established in some cases. To illustrate, the default display page default background color in the above initialization is WHITE. If there is no hidden field named bgcolor with a valid Name clause, white will be used. However, if there is a value passed to the Manager, it will override the default value.

Allowances are made from various naming preferences in the form's hidden field NAME clause. Then all spaces, dashes, and underscores are taken out and the supplied names are changed to all lower case. The following NAME clauses will all be equivalent: FirstName, firstname, FIRSTNAME, First Name, first_name, firstNAME, and any variation of this theme.

The next program call is to GetFormData(). This function starts by determining if a GET or POST method was used when submitting the form. If a POST method was used, an array named $HTTP_POST_VARS is loaded, and $HTTP_GET_VARS is loaded if a GET method was used. The appropriate array is transferred to the $FormVariables array, so there is no additional testing for submission method required.

Next, on the hit parade is a call to FixArrays(). This function loops through the $FormVariables array. When a form is submitted, there is no way to determine if a particular name/value pair started life as a hidden field or was entered by the Web surfer. While looping through the array, the converted name value is checked against the $SystemVariables name properties. If a match is found, the value is transferred to the $SystemVariables array and removed from the $FormVariables array. At the end of this function, the $SystemVariables array contains the default control variables plus any information from hidden fields that override the default values. The $FormVariables array contains only name/value pairs pertaining to user inputs. Pretty clever even for the Phanatic!

MakeHTMLtop() simply generates the common top-of-page HTML. Modify this function to somewhat change the application's look and feel.

The call to LegalDomain() was added since the previous column. If you don't control who can use your Phorm Manager, anyone can use it as a gateway. This is probably not a good idea. The program starts with the initialization of the $AcceptableDomains array. Something like:

$AcceptableDomains = 
       array("localhost","phpphanatic.com","iloveac.com");

The LegalDomain() function uses the environment variable $HTTP_REFERER, coupled with the parse_url() function, to extract the domain of the caller. If the domain is not in the list, a warning message is issued and processing is terminated. The statements:

  $URLparts = parse_url($HTTP_REFERER);
  $Domain = strtolower($URLparts[host]);

are followed by a traversal of the $AcceptableDomains array.

Do me a test

The Phorm Manager's task management is controlled by, what else, a hidden field named "formaction," or "FormAction" if you prefer.

<!-- FormAction can be Test or Mail, with Mail being the default -->
<INPUT TYPE="HIDDEN" NAME="FormAction" VALUE="Test">

Only the first letter is needed in the FormAction value clause, but we can keep the shortcut a secret. Set this variable's value to T to test the form without actually e-mailing anything.

Switch hitter

We'll use a PHP switch structure to control program flow.

The application's traffic cop is the switch statement. The switch construct falls into the class of PHP statements called "syntactic candy." They don't provide anything you couldn't do without them, but they make programming easier, cleaner, and more self-documenting. The ternary condition the Phanatic loves is another example of syntactic candy.

There is no equivalent to PHP's switch statement in Perl -- unfortunately -- but there is one in C. Here is the switch road map:

switch ($Action) {
case "M": # Action is to mail results to the recipient
# Check for data entry errors
Check4Errors($SystemVariables,$FormVariables,$Errors);
if ($Errors) { # If there were errors, process them.
ProcessErrors($HTML,$Errors);
break;
} # End of if ($Errors)
SendEmail($HTML,$Result,$SystemVariables,$FormVariables,
$AcknowledgementSent,$LongestName);
$Redirect = $SystemVariables[redirect];
if ($Redirect) {
header("Location: $Redirect");
exit;
} else {
if ($Result)
$HTML.="Mail Successfully Sent to $SystemVariables[recipient]\n";
if ($AcknowledgementSent)
$HTML.="<BR>Acknowledgement Successfully Sent to $AcknowledgementSent\n";
$HTML.="<P>The following are the name/value pairs of data submitted\n";
DisplayArrayVariables($FormVariables,$HTML);
}
break;
case "T": # Action is Test form
# Check for data entry errors
Check4Errors($SystemVariables,$FormVariables,$Errors);
if ($Errors) { # If there were errors, process them.
ProcessErrors($HTML,$Errors);
} # End of if ($Errors)
$HTML .= "<H3><FONT COLOR=\"RED\">Form Variables</FONT>\n";
$HTML .= "submitted using the \"$Method\" method.</H3>\n";
DisplayArrayVariables($FormVariables,$HTML); #$Display variables);
$HTML .= "<H3><FONT COLOR=\"RED\">System Variables</FONT></H3>\n";
DisplayArrayVariables($SystemVariables,$HTML); #$Display variables);
$HTML .= "<H3><FONT COLOR=\"RED\">Environment Variables</FONT></H3>\n";
DisplayArrayVariables($HTTP_ENV_VARS,$HTML); #$Display variables);
break;
default: # In case there is no "M" or "T"
$HTML .= "<CENTER><H2>Invalid Action</H2></CENTER>\n";
} # End of switch ($Action)

Finally followed by:

MakeHTMLbottom($HTML,$SystemVariables);
print $HTML;
exit;

If you understand the logic of a handful of lines, you understand what makes this 400+ line script work.

The HTML code is accumulated in the variable $HTML, which is passed by reference to the function adding HTML. Displaying the variable once at the end of the program saves a great deal of I/O overhead.

Program control using hidden fields

A template is a good place to start when designing a new form to be processed by the Phorm Manager. Here is a link to a typical template.

The template contains the following hidden fields. The comment line about the hidden field, or group, should be self-explanatory.

<!-- Recipient receives emailed from variable and is only required field. -->
<INPUT TYPE="HIDDEN" NAME="Recipient" VALUE="urb@usats.com">

<!-- To send an email acknowledgement to submitter the hidden field -->
<!-- SendAcknowledgement must be set to "Yes". In addition, the submitter's -->
<!-- email address must be entered in a field name "UserEmail", case matters.-->
<INPUT TYPE="HIDDEN" NAME="SendAcknowledgement" VALUE="Yes">

<!-- A comma separated list of all fields that may not have null values. -->
<INPUT TYPE="HIDDEN" NAME="Required" VALUE="FirstName,LastName">

<!-- A comma separated list of all fields requiring email address validation.-->
<INPUT TYPE="HIDDEN" NAME="CheckEmail" VALUE="TestEmailAddress">

<!-- A comma separated list of fields that must contain numeric data. -->
<INPUT TYPE="HIDDEN" NAME="CheckNumeric" VALUE="NumberField">

<!-- A comma separated list of fields that must contain valid zip codes. -->
<INPUT TYPE="HIDDEN" NAME="CheckZipCode" VALUE="ZipCode">

<!-- FormAction can be Test, or Mail. Mail is the default value. -->
<INPUT TYPE="HIDDEN" NAME="FormAction" VALUE="Mail">

<!-- The following four optional parameters are used in the body tag. -->
<INPUT TYPE="HIDDEN" NAME="TextColor" VALUE="BLUE">
<INPUT TYPE="HIDDEN" NAME="BGcolor" VALUE="WHITE">
<INPUT TYPE="HIDDEN" NAME="LinkColor" VALUE="GREEN">
<INPUT TYPE="HIDDEN" NAME="VlinkColor" VALUE="RED">
<!-- The following two optional parameters are for the bottom of page link. -->
<INPUT TYPE="HIDDEN" NAME="ReturnLinkURL" VALUE="http://oreilly.com">
<INPUT TYPE="HIDDEN" NAME="ReturnLinkTitle"
VALUE="The O'Reilly Home Page">
<!-- Transition to the following URL if there are no error. -->
<INPUT TYPE="HIDDEN" NAME="Redirect" VALUE="">
<!-Heading names must begin with a "H" and be followed only by numbers -->
<INPUT TYPE="HIDDEN" NAME="H01"
VALUE="==================== Phorm Manager ====================">

The headings require some additional explanation. Sometimes, especially with long forms, it's desirable to have section headings. When the submitted fields are displayed, both on the screen and in the e-mail, the fields are listed in the order they were displayed on the form page, from left to right and top to bottom. Any heading fields must therefore be inserted in the appropriate place. You can see the effect of heading fields in the demo form. The system determines heading fields by their name. The first character in the NAME clause must be an H, either upper or lower case. This letter must be immediately be followed by between one and three numeric digits.

Pages: 1, 2, 3

Next Pagearrow




Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!


Sponsored by: