Skip to content

Instantly share code, notes, and snippets.

@Mwamitovi
Created January 29, 2025 06:33
Show Gist options
  • Save Mwamitovi/e74955db0792fc6f21967065f77a10cf to your computer and use it in GitHub Desktop.
Save Mwamitovi/e74955db0792fc6f21967065f77a10cf to your computer and use it in GitHub Desktop.
<?php
// Chapter-10: Exercises
// Question-1
// 1. Make a web page that uses a cookie to keep track of how many times a user has viewed the page.
// The first time a particular user looks at the page, it should print something like “Number of views: 1.”
// The second time the user looks at the page, it should print “Number of views: 2,” and so on.
// Answer-1
$view_count = 1 + ($_COOKIE['view_count'] ?? 0);
setcookie('view_count', $view_count);
print "<p>Hi! Number of times you've viewed this page: $view_count.</p>";
// Question-2
// 2. Modify the web page from the first exercise so that it prints out a special message on the 5th, 10th,
// and 15th times the user looks at the page. Also modify it so that on the 20th time the user looks at the page,
// it deletes the cookie and the page count starts over.
// Answer-2
$view_count = 1 + ($_COOKIE['view_count'] ?? 0);
if ($view_count == 20) {
// An empty value for setcookie() removes the cookie
setcookie(
'view_count',
''
);
$msg = "<p>Time to start over.</p>";
} else {
setcookie('view_count', $view_count);
$msg = "<p>Hi! Number of times you've viewed this page: $view_count.</p>";
if ($view_count == 5) {
$msg .= "<p>This is your fifth visit.</p>";
} elseif ($view_count == 10) {
$msg .= "<p>This is your tenth visit. You must like this page.</p>";
} elseif ($view_count == 15) {
$msg .= "<p>This is your fifteenth visit. " .
"Don't you have anything else to do?</p>";
}
}
print $msg;
// Question-3
// 3. Write a PHP program that displays a form for a user to pick his favorite color from a list of colors.
// Make another page whose background color is set to the color that the user picks in the form.
// Store the color value in $_SESSION so that both pages can access it.
// Answer-3
// The color-picking page:
// Start sessions first thing so we can use $_SESSION freely later
session_start();
// Load the form helper class
require 'FormHelper.php';
$colors = array(
'ff0000' => 'Red',
'ffa500' => 'Orange',
'ffffff' => 'Yellow',
'008000' => 'Green',
'0000ff' => 'Blue',
'4b0082' => 'Indigo',
'663399' => 'Rebecca Purple'
);
// 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);
}
} else {
// The form wasn't submitted, so display
show_form();
}
function show_form($errors = array())
{
global $colors;
// 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 'color-form.php';
}
function validate_form()
{
$input = array();
$errors = array();
// color must be a valid color
$input['color'] = $_POST['color'] ?? '';
if (!array_key_exists($input['color'], $GLOBALS['colors'])) {
$errors[] = 'Please select a valid color.';
}
return array($errors, $input);
}
function process_form($input)
{
global $colors;
$_SESSION['background_color'] = $input['color'];
print '<p>Your color has been set.</p>';
}
// The code relies on the FormHelper.php file discussed in Chapter 7.
// The color-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>
<td>Favorite Color:</td>
<td><?= $form->select($colors, ['name' => 'color']) ?></td>
</tr>
<tr>
<td colspan="2" align="center">
<?= $form->input('submit', [
'name' => 'set',
'value' => 'Set Color'
]) ?>
</td>
</tr>
</table>
<?php
// The page with background color set:
// Start sessions first thing so we can use $_SESSION freely later
session_start();
?>
<html>
<head>
<title>Background Color Example</title>
<body style="background-color:<?= $_SESSION['background_color'] ?>">
<p>What color did you pick?</p>
</body>
</html><?php
// Question-4
// 4. Write a PHP program that displays an order form. The order form should list six products.
// Next to each product name there should be a text box into which a user can enter how many of
// that product she wants to order.
// When the form is submitted, the submitted form data should be saved into the session.
// Make another page that displays the contents of the saved order, a link back to the order form page,
// and a Check Out button. If the link back to the order form page is clicked, the order form page should be
// displayed with the saved order quantities from the session in the text boxes.
// When the Check Out button is clicked, the order should be cleared from the session.
// Answer-4
// The ordering page:
session_start();
// 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.
$products = [
'cuke' => 'Braised Sea Cucumber',
'stomach' => "Sauteed Pig's Stomach",
'tripe' => 'Sauteed Tripe with Wine Sauce',
'taro' => 'Stewed Pork with Taro',
'giblets' => 'Baked Giblets with Salt',
'abalone' => 'Abalone with Marrow and Duck Feet'
];
// 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_form2();
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_form2();
}
function show_form2($errors = array())
{
global $products;
$defaults = array();
// Start out with 0 as a default
foreach ($products as $code => $label) {
$defaults["quantity_$code"] = 0;
}
// If quantities are in the session, use those
if (isset($_SESSION['quantities'])) {
foreach ($_SESSION['quantities'] as $field => $quantity) {
$defaults[$field] = $quantity;
}
}
$form = new FormHelper($defaults);
// All the HTML and form display is in a separate file for clarity
include 'order-form.php';
}
function validate_form2()
{
global $products;
$input = array();
$errors = array();
// For each quantity box, make sure the value is
// a valid integer >= 0
foreach ($products as $code => $name) {
$field = "quantity_$code";
$input[$field] = filter_input(
INPUT_POST,
$field,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 0]]
);
if (is_null($input[$field]) || ($input[$field] === false)) {
$errors[] = "Please enter a valid quantity for $name.";
}
}
return array($errors, $input);
}
function process_form2($input)
{
$_SESSION['quantities'] = $input;
print "Thank you for your order.";
}
// The code relies on the FormHelper.php file discussed in Chapter 7.
// The order-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>Product</th>
<td>Quantity</td>
</tr>
<?php foreach ($products as $code => $name) { ?>
<tr>
<td><?= htmlentities($name) ?>:</td>
<td><?= $form->input('text', ['name' => "quantity_$code"]) ?></td>
</tr>
<?php } ?>
<tr>
<td colspan="2" align="center"><?= $form->input('submit', ['value' => 'Order']) ?>
</td>
</tr>
</table>
</form><?php
// The checkout page:
session_start();
// The same products from the order page
$products = [
'cuke' => 'Braised Sea Cucumber',
'stomach' => "Sauteed Pig's Stomach",
'tripe' => 'Sauteed Tripe with Wine Sauce',
'taro' => 'Stewed Pork with Taro',
'giblets' => 'Baked Giblets with Salt',
'abalone' => 'Abalone with Marrow and Duck Feet'
];
// Simplified main page logic without form validation
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
process_form3();
} else {
// The form wasn't submitted, so display
show_form3();
}
function show_form3()
{
global $products;
// The "form" is just a single submit button, so we won't use
// FormHelper and just inline all the HTML here
if (isset($_SESSION['quantities']) && (count($_SESSION['quantities']) > 0)) {
print "<p>Your order:</p><ul>";
foreach ($_SESSION['quantities'] as $field => $amount) {
list($junk, $code) = explode('_', $field);
$product = $products[$code];
print "<li>$amount $product</li>";
}
print "</ul>";
print '<form method="POST" action=' .
htmlentities($_SERVER['PHP_SELF']) . '>';
print '<input type="submit" value="Check Out" />';
print '</form>';
} else {
print "<p>You don't have a saved order.</p>";
}
// This assumes the order form page is saved as "order.php"
print '<a href="order.php">Return to Order page</a>';
}
function process_form3()
{
// This removes the data from the session
unset($_SESSION['quantities']);
print "<p>Thanks for your order.</p>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment