!doctype HTML Head Style .Error /style /head Body
!doctype HTML Head Style .Error /style /head Body
Run following code, explain what you understand. Explain each function variable.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
// $_SERVER['REQUEST_METHOD'] returns the request method used to access the page (such
as POST)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/* PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". */
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
// test_input() tests the value of input then save and post the value
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
// preg_match – this function is used to perform a pattern match on a string.
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
// if input field is empty then print email is required.
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
// if input field is empty then print gender is required.
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
// test_input() function tests the value of input then return the value
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
// method =”post” is use to collect save the form data after submitting HTML form into PHP.
// The htmlspecialchars() function converts some predefined characters to HTML entities.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
// php echo print the value of $nameErr after submitting an empty field, it shows error.
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Assignment # 1 WDD-13/9/19
</body>
</html>