Created
January 29, 2025 06:07
-
-
Save Mwamitovi/ac2534b4a1e43b5ada7cf6abe257b684 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Chapter-7: Exercises | |
// Question-1 | |
// 1. What does $_POST look like when the following form is submitted with the third option in the Braised Noodles menu selected, | |
// the first and last options in the Sweet menu selected, and 4 entered into the text box? ?> | |
<form method="POST" action="order.php"> | |
Braised Noodles with: <select name="noodle"> | |
<option>crab meat</option> | |
Chapter Summary | 153 | |
<option>mushroom</option> | |
<option>barbecued pork</option> | |
<option>shredded ginger and green onion</option> | |
</select> | |
<br /> | |
Sweet: <select name="sweet[]" multiple> | |
<option value="puff"> Sesame Seed Puff | |
<option value="square"> Coconut Milk Gelatin Square | |
<option value="cake"> Brown Sugar Cake | |
<option value="ricemeat"> Sweet Rice and Meat | |
</select> | |
<br /> | |
Sweet Quantity: <input type="text" name="sweet_q"> | |
<br /> | |
<input type="submit" name="submit" value="Order"> | |
</form><?php | |
// Answer-1 | |
$_POST['noodle'] = 'barbecued pork'; | |
$_POST['sweet'] = ['puff', 'ricemeat']; | |
$_POST['sweet_q'] = '4'; | |
$_POST['submit'] = 'Order'; | |
// Question-2 | |
// 2. Write a process_form() function that prints out all submitted form parameters and their values. | |
// You can assume that form parameters have only scalar values. | |
// Answer-2 | |
// Since this is operating on form data, it looks directly at $_POST instead of a validated $input array | |
function process_form() | |
{ | |
print '<ul>'; | |
foreach ($_POST as $k => $v) { | |
print '<li>' . htmlentities($k) . '=' . htmlentities($v) . '</li>'; | |
} | |
print '</ul>'; | |
} | |
// Question-3 | |
// 3. Write a program that does basic arithmetic. | |
// Display a form with text box inputs for two operands and a <select> menu to choose an operation: addition, subtraction, multiplication, or division. | |
// Validate the inputs to make sure that they are numeric and appropriate for the chosen operation. | |
// The processing function should display the operands, the operator, and the result. | |
// For example, if the operands are 4 and 2 and the operation is multiplication, | |
// the processing function should display something like 4 * 2 = 8. | |
// Answer-3 | |
// This assumes FormHelper.php is in the same directory as this file. | |
require 'FormHelper.php'; | |
// Set up the arrays of choices in the select menu. | |
// This is needed in display_form(), validate_form(), and process_form(), so it is declared in the global scope. | |
$ops = array('+', '-', '*', '/'); | |
// The main page logic: | |
// - If the form is submitted, validate and then process or redisplay | |
// - If it's not submitted, display | |
if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
// If validate_form() returns errors, pass them to show_form() | |
list($errors, $input) = validate_form(); | |
if ($errors) { | |
show_form($errors); | |
} else { | |
// The submitted data is valid, so process it | |
process_form($input); | |
// And then show the form again to do another calculation | |
show_form(); | |
} | |
} else { | |
// The form wasn't submitted, so display | |
show_form(); | |
} | |
function show_form($errors = array()) | |
{ | |
$defaults = array( | |
'num1' => 2, | |
'op' => 2, // the index of '*' in $ops | |
'num2' => 8 | |
); | |
// Set up the $form object with proper defaults | |
$form = new FormHelper($defaults); | |
// All the HTML and form display is in a separate file for clarity | |
include 'math-form.php'; | |
} | |
function validate_form() | |
{ | |
$input = array(); | |
$errors = array(); | |
// op is required | |
$input['op'] = $GLOBALS['ops'][$_POST['op']] ?? ''; | |
if (!in_array($input['op'], $GLOBALS['ops'])) { | |
$errors[] = 'Please select a valid operation.'; | |
} | |
// num1 and num2 must be numbers | |
$input['num1'] = filter_input(INPUT_POST, 'num1', FILTER_VALIDATE_FLOAT); | |
if (is_null($input['num1']) || ($input['num1'] === false)) { | |
$errors[] = 'Please enter a valid first number.'; | |
} | |
$input['num2'] = filter_input(INPUT_POST, 'num2', FILTER_VALIDATE_FLOAT); | |
if (is_null($input['num2']) || ($input['num2'] === false)) { | |
$errors[] = 'Please enter a valid second number.'; | |
} | |
// Can't divide by zero | |
if (($input['op'] == '/') && ($input['num2'] == 0)) { | |
$errors[] = 'Division by zero is not allowed.'; | |
} | |
return array($errors, $input); | |
} | |
function process_form2($input) | |
{ | |
$result = 0; | |
if ($input['op'] == '+') { | |
$result = $input['num1'] + $input['num2']; | |
} else if ($input['op'] == '-') { | |
$result = $input['num1'] - $input['num2']; | |
} else if ($input['op'] == '*') { | |
$result = $input['num1'] * $input['num2']; | |
} else if ($input['op'] == '/') { | |
$result = $input['num1'] / $input['num2']; | |
} | |
$message = | |
"{$input['num1']} {$input['op']} {$input['num2']} = $result"; | |
print "<h3>$message</h3>"; | |
} | |
// The code relies on the FormHelper.php file discussed in Chapter 7. | |
// The mathform.php file referenced, which displays the form HTML, contains: ?> | |
<form method="POST" action="<?= $form->encode($_SERVER['PHP_SELF']) ?>"> | |
<table> | |
<?php if ($errors) { ?> | |
<tr> | |
<td>You need to correct the following errors:</td> | |
<td> | |
<ul> | |
<?php foreach ($errors as $error) { ?> | |
<li><?= $form->encode($error) ?></li> | |
<?php } ?> | |
</ul> | |
</td> | |
<?php } ?> | |
<tr> | |
<td>First Number:</td> | |
<td><?= $form->input('text', ['name' => 'num1']) ?></td> | |
</tr> | |
<tr> | |
<td>Operation:</td> | |
<td><?= $form->select($GLOBALS['ops'], ['name' => 'op']) ?></td> | |
</tr> | |
<tr> | |
<td>Second Number:</td> | |
<td><?= $form->input('text', ['name' => 'num2']) ?></td> | |
</tr> | |
<tr> | |
<td colspan="2" align="center"><?= $form->input( | |
'submit', | |
['value' => 'Calculate'] | |
) ?> | |
</td> | |
</tr> | |
</table><?php | |
// Question-4 | |
// 4. Write a program that displays, validates, and processes a form for entering information about a package to be shipped. | |
// The form should contain inputs for the from and to addresses for the package, dimensions of the package, and weight of the package. | |
// The validation should check (at least) that the package weighs no more than 150 pounds and that no dimension of the package is more than 36 inches. | |
// You can assume that the addresses entered on the form are both US addresses, | |
// but you should check that a valid state and a zip code with valid syntax are entered. | |
// The processing function in your program should print out the information about the package in an organized, formatted report. | |
// Answer-4 | |
// This assumes FormHelper.php is in the same directory as this file. | |
require 'FormHelper.php'; | |
// Set up the array of choices in the select menu. | |
// This is needed in display_form(), validate_form(), | |
// and process_form(), so it is declared in the global scope. | |
$states = [ 'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', | |
'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', | |
'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', | |
'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', | |
'WY' ]; | |
// The main page logic: | |
// - If the form is submitted, validate and then process or redisplay | |
// - If it's not submitted, display | |
if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
// If validate_form() returns errors, pass them to show_form() | |
list($errors, $input) = validate_form(); | |
if ($errors) { | |
show_form($errors); | |
} else { | |
// The submitted data is valid, so process it | |
process_form2($input); | |
} | |
} else { | |
// The form wasn't submitted, so display | |
show_form(); | |
} | |
function show_form2($errors = array()) | |
{ | |
// Set up the $form object with proper defaults | |
$form = new FormHelper(); | |
// All the HTML and form display is in a separate file for clarity | |
include 'shipping-form.php'; | |
} | |
function validate_form2() | |
{ | |
$input = array(); | |
$errors = array(); | |
foreach (['from', 'to'] as $addr) { | |
// Check required fields | |
foreach (['Name' => 'name', 'Address 1' => 'address1', 'City' => 'city', 'State' => 'state'] as $label => $field) { | |
$input[$addr . '_' . $field] = $_POST[$addr . '_' . $field] ?? ''; | |
if (strlen($input[$addr . '_' . $field]) == 0) { | |
$errors[] = "Please enter a value for $addr $label."; | |
} | |
} | |
// Check state | |
$input[$addr . '_state'] = | |
$GLOBALS['states'][$input[$addr . '_state']] ?? ''; | |
if (!in_array($input[$addr . '_state'], $GLOBALS['states'])) { | |
$errors[] = "Please select a valid $addr state."; | |
} | |
// Check zip code | |
$input[$addr . '_zip'] = filter_input( | |
INPUT_POST, | |
$addr . '_zip', | |
FILTER_VALIDATE_INT, | |
[ | |
'options' => [ | |
'min_range' => 10000, | |
'max_range' => 99999 | |
] | |
] | |
); | |
if (is_null($input[$addr . '_zip']) || ($input[$addr . '_zip'] === false)) { | |
$errors[] = "Please enter a valid $addr ZIP"; | |
} | |
// Don't forget about address2! | |
$input[$addr . '_address2'] = $_POST[$addr . '_address2'] ?? ''; | |
} | |
// height, width, depth, weight must all be numbers > 0 | |
foreach (['height', 'width', 'depth', 'weight'] as $field) { | |
$input[$field] = filter_input(INPUT_POST, $field, FILTER_VALIDATE_FLOAT); | |
// Since 0 is not valid, we can just test for truth rather than | |
// null or exactly false | |
if (!($input[$field] && ($input[$field] > 0))) { | |
$errors[] = "Please enter a valid $field."; | |
} | |
} | |
// Check weight | |
if ($input['weight'] > 150) { | |
$errors[] = "The package must weigh no more than 150 lbs."; | |
} | |
// Check dimensions | |
foreach (['height', 'width', 'depth'] as $dim) { | |
if ($input[$dim] > 36) { | |
$errors[] = "The package $dim must be no more than 36 inches."; | |
} | |
} | |
return array($errors, $input); | |
} | |
function process_form3($input) | |
{ | |
// Make a template for the report | |
$tpl = <<<HTML | |
<p>Your package is {height}" x {width}" x {depth}" and weighs {weight} lbs.</p> | |
<p>It is coming from:</p> | |
<pre> | |
{from_name} | |
{from_address} | |
{from_city}, {from_state} {from_zip} | |
</pre> | |
<p>It is going to:</p> | |
<pre> | |
{to_name} | |
{to_address} | |
{to_city}, {to_state} {to_zip} | |
</pre> | |
HTML; | |
// Adjust addresses in $input for easier output | |
foreach (['from', 'to'] as $addr) { | |
$input[$addr . '_address'] = $input[$addr . '_address1']; | |
if (strlen($input[$addr . '_address2'])) { | |
$input[$addr . '_address'] .= "\n" . $input[$addr . '_address2']; | |
} | |
} | |
// Replace each template variable with the corresponding value | |
// in $input | |
$html = $tpl; | |
foreach ($input as $k => $v) { | |
$html = str_replace('{' . $k . '}', $v, $html); | |
} | |
// Print the report | |
print $html; | |
} | |
// The code relies on the FormHelper.php file discussed in Chapter 7. | |
// The shipping-form.php file referenced, which displays the form HTML, contains: ?> | |
<form method="POST" action="<?= $form->encode($_SERVER['PHP_SELF']) ?>"> | |
<table> | |
<?php if ($errors) { ?> | |
<tr> | |
<td>You need to correct the following errors:</td> | |
<td> | |
<ul> | |
<?php foreach ($errors as $error) { ?> | |
<li><?= $form->encode($error) ?></li> | |
<?php } ?> | |
</ul> | |
</td> | |
<?php } ?> | |
<tr> | |
<th>From:</th> | |
<td></td> | |
</tr> | |
<tr> | |
<td>Name:</td> | |
<td><?= $form->input('text', ['name' => 'from_name']) ?></td> | |
</tr> | |
<tr> | |
<td>Address 1:</td> | |
<td><?= $form->input('text', ['name' => 'from_address1']) ?></td> | |
</tr> | |
<tr> | |
<td>Address 2:</td> | |
<td><?= $form->input('text', ['name' => 'from_address2']) ?></td> | |
</tr> | |
<tr> | |
<td>City:</td> | |
<td><?= $form->input('text', ['name' => 'from_city']) ?></td> | |
</tr> | |
<tr> | |
<td>State:</td> | |
<td><?= $form->select($GLOBALS['states'], ['name' => 'from_state']) ?> | |
</td> | |
</tr> | |
<tr> | |
<td>ZIP:</td> | |
<td><?= $form->input('text', ['name' => 'from_zip', 'size' => 5]) ?> | |
</td> | |
</tr> | |
<tr> | |
<th>To:</th> | |
<td></td> | |
</tr> | |
<tr> | |
<td>Name:</td> | |
<td><?= $form->input('text', ['name' => 'to_name']) ?></td> | |
</tr> | |
<tr> | |
<td>Address 1:</td> | |
<td><?= $form->input('text', ['name' => 'to_address1']) ?></td> | |
</tr> | |
<tr> | |
<td>Address 2:</td> | |
<td><?= $form->input('text', ['name' => 'to_address2']) ?></td> | |
</tr> | |
<tr> | |
<td>City:</td> | |
<td><?= $form->input('text', ['name' => 'to_city']) ?></td> | |
</tr> | |
<tr> | |
<td>State:</td> | |
<td><?= $form->select($GLOBALS['states'], ['name' => 'to_state']) ?> | |
</td> | |
</tr> | |
<tr> | |
<td>ZIP:</td> | |
<td><?= $form->input('text', ['name' => 'to_zip', 'size' => 5]) ?> | |
</td> | |
</tr> | |
<tr> | |
<th>Package:</th> | |
<td></td> | |
</tr> | |
<tr> | |
<td>Weight:</td> | |
<td><?= $form->input('text', ['name' => 'weight']) ?></td> | |
</tr> | |
<tr> | |
<td>Height:</td> | |
<td><?= $form->input('text', ['name' => 'height']) ?></td> | |
</tr> | |
<tr> | |
<td>Width:</td> | |
<td><?= $form->input('text', ['name' => 'width']) ?></td> | |
</tr> | |
<tr> | |
<td>Depth:</td> | |
<td><?= $form->input('text', ['name' => 'depth']) ?></td> | |
</tr> | |
<tr> | |
<td colspan="2" align="center"> | |
<?= $form->input('submit', ['value' => 'Ship!']) ?> | |
</td> | |
</tr> | |
</table> | |
</form><?php | |
// Question-5 | |
// 5. (Optional) Modify your process_form() function that enumerates all submitted form parameters | |
// and their values so that it correctly handles submitted form parameters that have array values. | |
// Remember, those array values could themselves contain arrays. | |
// Answer-5 | |
function print_array($ar) | |
{ | |
print '<ul>'; | |
foreach ($ar as $k => $v) { | |
if (is_array($v)) { | |
print '<li>' . htmlentities($k) . ':</li>'; | |
print_array($v); | |
} else { | |
print '<li>' . htmlentities($k) . '=' . htmlentities($v) . '</li>'; | |
} | |
} | |
print '</ul>'; | |
} | |
/* Since this is operating on form data, it looks directly at $_POST | |
instead of a validated $input array */ | |
function process_form4() | |
{ | |
print_array($_POST); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment