PHP QuickStart Guide (2015)

Appendix B: Completed Code

<?php
/*** if the form was submitted, get the input values ***/
if (isset ($_POST['sendbutton'])) {
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $msg = $_POST['msg'];
    /*** test for required inputs ***/
    if (empty($fname) || empty($lname) ||
        empty($email) || empty($msg)) {
        $error = TRUE;
    } else {
        /*** send email ***/
        $recipient = 'me@mydomain.com'; //set to your email
        $subject = 'Website contact';
        $body = "The following message was sent";
        $body .= " via your website contact form:\n\n";
        $body .= "Name: $fname $lname\n";
        $body .= "Email: $email\n";
        if (empty($phone) == FALSE) {
            $body .= "Phone: $phone\n";
        }
        $body .= "\n$msg";
        $headers = "From: webform@mydomain.com\r\n";
        //change mydomain.com to your domain
        $headers .= "Reply-to: $email\r\n\r\n";
        $sent = (mail($recipient, $subject, $body, $headers));
        if ($sent) {
            $success = TRUE;
        }    // end the if construct
    }    //end the if/else construct
}    //end the if construct
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Contact Form</title>
</head>
<body>
<?php if ($success): ?>
<!-- EMAIL SENT. PRINT THANK YOU PAGE →
<div style="margin: auto; text-align:center">
<h2>Thank you for contacting us!</h2>
Your email has been sent and we'll respond as quickly as possible.
</div>
<?php else: ?>
<!-- EMAIL NOT SENT. FORM NOT SUBMITTED OR INPUT MISSING →
<?php if ($error): ?>
<!-- INPUT MISSING. DISPLAY ERROR MESSAGE →
<div style="font-weight:bold; color:#ff0000;">
Please enter input for each field with a <strong>bold</strong>label.
</div>
<?php endif; ?>
<p>If you have questions about this site, please use the form below to contact us, so that we can provide the best possible answers.</p>
<p> Fields with <strong>bold</strong> labels are required.</p>
<form method="post" action="./contactform.php">
<strong>First Name</strong> 
<input type="text" name="fname" size="20" value="<?= $fname ?>"><br>
<strong>Last Name</strong> 
<input type="text" name="lname" size="20" value="<?= $lname ?>"><br>
Phone 
<input type="text" name="phone" size="20" value="<?= $phone ?>"><br>
<strong>Email Address</strong> 
<input type="text" name="email" size="20" value="<?= $email ?>"><br>
<strong>Type your question below:</strong><br>
<textarea name="msg" cols="50" rows="10"><?= $msg ?></textarea><br>
<input type="submit" name="sendbutton" value="Send">
<?php endif; ?>
</body>
</html>