Form Evaluation With PHP
A meaningful use of PHP is the evaluation of forms.
<form class="form-horizontal" action="f.html" method="post">
<div class="form-group">
<label for="inputName" class="col-xm-3 control-label">Name</label>
<div class="col-xm-9">
<input type="text" class="form-control" id="inputName" name="name" placeholder="Name" value="">
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-xm-3 control-label">E-mail-address</label>
<div class="col-xm-9">
<input type="email" class="form-control" id="inputEmail" name="email" placeholder="E-mail-address" value="">
</div>
</div>
<div class="form-group">
<div class="col-xm-offset-3 col-xm-9">
<div class="checkbox">
<label><input type="checkbox" id="checkExpert" name="expert" value="1"> Expert</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xm-offset-3 col-xm-9">
<button type="submit" class="btn btn-default" name="sent" value="1">Send</button>
</div>
</div>
</form>
# <form … method="post"> → Data is in the array $_POST
$name_html = $email_html = $expert = '';
if (isset($_POST['sent']) && $_POST['sent'] == '1') {
# This is where we end up when the form has been sent:
# Test transcript with all form data
echo '<pre>' . print_r($_POST, true) . '</pre>';
# 1. Error handling, e.g.
$errors = '';
if (!isset($_POST['name']) || $_POST['name'] == '') {
$errors .= 'Error: No name specified!';
}
if ($errors) {
echo '<p class="tucbox-tip-danger">' . htmlspecialchars($errors) . '</p>';
} else {
# 2. Data processing - output here
$name_html = htmlspecialchars($_POST['name']);
$email_html = htmlspecialchars($_POST['email']);
if (isset($_POST['expert']) && $_POST['expert'] == '1') {
$expert_html = 'Yes';
$expert = ' checked';
} else {
$expert_html = 'No';
}
echo "<p>Transmitted form data: Name = $name_html, E-mail = $email_html, Expert = $expert_html</p>";
# Process data, e.g. write to database or file ...
# or in this case: send all form data by e-mail:
$content = '';
foreach ($_POST as $name => $value) { # alle gesendeten Formulardaten
if ($value != '') { # If value exists, save in content
$content .= sprintf("%20s : %s\n", $name, $value);
}
}
if ($content != '') { # if content, then send mail
require_once('php/mail.inc');
$to = 'fri@hrz.tu-chemnitz.de'; # Recipient's e-mail address
$mailtext = 'Form inputs off ' . $_SERVER['SCRIPT_URI'] . "\n\n" . $content;
$ok = tuc_mail($to, $to, 'Form input', $mailtext);
if ($ok === TRUE) {
echo "E-mail was sent.";
} else {
echo "Error while sending: " . htmlspecialchars($ok);
}
}
}
}
See also: