SakhaliaNetHome PageSahara TerritoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Exercises (X)

PHP Exercise #19

Counter with a cookie

Set a cookie (not a session) that allows to track the number of times that an user has visited the webpage where the cookie is called. Make the program to print a special message when the number of views is 5, 10 and 15, and delete the cookie when it reaches 20, hence resetting the counter.

<?php
// Code placed at the beginning of the page
$message = '';
$page_count = $_COOKIE['page_count'] + 1;
if ($page_count == 20) {
// An empty value deletes the cookie
setcookie('page_count','');
$message = "Time to start over.";
} else {
setcookie('page_count', $page_count);
$message = "Number of views: $page_count";
if ($page_count == 5) {
$message = "This is your fifth visit.";
} elseif ($page_count == 10) {
$message = "This is your tenth visit. Aren't you sick of this page yet?";
} elseif ($page_count == 15) {
$message = "This is your fifteenth visit. Don't you have anything better to do?";
}
}
?>

<?php
// Code placed anywhere in the page
print $message;
?>
Number of views: 1

PHP Exercise #20

Saving a color in a session

Write a program that shows a form that allows an user to pick a color from a list. Create a different webpage whose background color is the color selected by the user. Store the value of the color in $_SESSION so both webpages can access it.

<?php
// Code placed at the beginning of both pages
session_start();
?>

<?php
// Code used on the test page to change CSS property background-color
// Disable background-image if needed
print 'background-color:' . $_SESSION['color'] . ';';
?>

<?php
// Code placed anywhere in the page
require 'scripts/formhelpers.php';
$colors = array('#ff0000' => 'red', '#ff6600' => 'orange',
'#ffff00' => 'yellow', '#00ff00' => 'green',
'#0000ff' => 'blue', '#ff00ff' => 'purple');
if (! array_key_exists('_submit_check', $_POST)) {
$_POST['_submit_check'] = 0;
}
if ($_POST['_submit_check']) {
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
process_form();
}
} else {
show_form();
}
function show_form($errors = '') {
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
if ($errors) {
print '<ul><li>';
print $errors;
print '</li></ul>';
}
print 'Color: ';
input_select('color', $_POST, $GLOBALS['colors']);
input_submit('submit', 'Select Color');
print '<input type="hidden" name="_submit_check" value="1"/>';
print '</form>';
}
function validate_form() {
$errors = array();
// The selected color must be valid
if (! array_key_exists($_POST['color'], $GLOBALS['colors'])) {
$errors = 'Please select a valid color.';
}
return $errors;
}
function process_form() {
$_SESSION['color'] = $_POST['color'];
print 'Your favorite color is: ' . $GLOBALS['colors'][$_SESSION['color']] . '<br/><br/>';
print 'Check the link to see the change: <a href="test_color.php">Color Test</a>';
}
?>
Color: