Your Favorite Color: The final code

  1. Post and Get
  2. Your Favorite Color

fields.phpi

<?php

class FormField {

public $value = null;

public $fieldName;

protected $submitted = false;

public function __construct($fieldName) {

$this->fieldName = $fieldName;

$this->clean();

}

public function answered() {

if ($this->submitted) {

if ($this->value === '') {

echo "<p>You need to enter a {$this->fieldName}!</p>\n";

} else {

return true;

}

}

return false;

}

protected function clean() {

if (isset($_POST[$this->fieldName])) {

$this->submitted = true;

$value = $_POST[$this->fieldName];

$value = trim($value);

$value = htmlentities($value);

$this->value = $value;

}

}

}

class ColorField extends FormField {

public function background() {

if ($this->value == 'white') {

$color = 'green';

} else {

$color = 'white';

}

return $color;

}

protected function clean() {

parent::clean();

if (isset($this->value)) {

$this->value = strtolower($this->value);

}

}

}

?>

The final code: color.php

<?php

include_once('/home/USERNAME/includes/fields.phpi');

$color = new ColorField('color');

$name = new FormField('name');

?>

<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Your Favorite Color</title>

<style>

body {

margin: 10em;

padding: 2em;

border: solid .2em green;

}

h1 {

text-align: center;

}

</style>

</head>

<body>

<h1>PHP Color Extravaganza</h1>

<?php IF ($color->answered() && $name->answered()):?>

<p style="color: <?php echo $color->value; ?>; background-color: <?php echo $color->background(); ?>">

You said your favorite color was <?php echo $color->value; ?>.

Thanks, <?php echo $name->value; ?>!

</p>

<?php

$recipient = 'yourname@example.com';

$subject = 'Favorite color of ' . $name->value;

$message = $name->value . ' said their favorite color was ' . $color->value . '.';

$message .= "\n\n";

$message .= "Browser: " . $_SERVER['HTTP_USER_AGENT'] . "\n";

$message .= "IP Address: " . $_SERVER['REMOTE_ADDR'] . "\n";

mail($recipient, $subject, $message);

?>

<?php ENDIF; ?>

<form method="post" action="color.php">

<p>

What is your favorite color?

<input type="text" name="color" value="<?php echo $color->value; ?>" />

</p>

<p>

What is your name?

<input type="text" name="name" value="<?php echo $name->value; ?>" />

</p>

<input type="submit" />

</form>

</body>

</html>

  1. Post and Get
  2. Your Favorite Color