Help folks out when your form fails

Your form has failed, and you’ve shown your visitor an error message asking them to contact you by email. Why not take it a step further and copy the contents of the form into an email message for them?

So here’s our form submit code.

[php]<?php
if (isset($_POST["frmSubmit"])) {
if(!isset($_POST["name"]) || !isset($_POST["email"])) {
header("Location: registration_sent.php?error=2");
} else {
$firstname = $_POST["name"];
$email = $_POST["email"];
$sTo = "email@example.com";
$sSubject = "Email from example.com contact form";
$sBody = "";
$sBody .= "CONTACT NAME: " . $name . "n";
$sBody .= "EMAIL: " . $email . "n";

if(mail($sTo,$sSubject,$sBody,$sHeaders)){
header("Location: contact-sent.php?error=0");
} else {
session_start();
$_SESSION[‘message’] = $sBody;
header("Location: contact-sent.php?error=1");
}

}
} else { ?>
Form HTML goes here
<?php } ?>[/php]

I’ll explain the submit code a bit. The first if statement checks if a form has been submitted. If so, the second if statement checks for the required fields, if they aren’t filled out we load our form sent page and display a missing fields error. Typically, I’d use the jQuery validation plugin nowadays, as opposed to server-side validation.

So, all our required fields are filled in, the next if statement handles submitting the form or sets up a PHP session to pass the contents of the form to the form submit page.

The form submit page handles all the “states”. Success, missing fields, or email error messages. Here’s the code that handles that.

[php]<?php if($_GET["error"]==0) { ?>
<p>Thanks for contacting us!</p>
<?php } else if($_GET["error"]==1) {
session_start();
$email_message = preg_replace( ‘/n|rn/’, ‘%0D%0A’, $_SESSION[‘message’]  );
$page_message = preg_replace( ‘/n|rn/’, ‘<br/>’, $_SESSION[‘message’]  );
echo "<p>We’re sorry, but we couldn’t send your message. We’ve copied your message and you can send it by email to <a href=’mailto:email@example.com?Subject=Email from example.com contact form&body=" . $email_message ."’>email@example.com</a>.</p><p>Here’s a copy of what you’re sending:</p><p>" . $page_message . "</p>";
} else if($_GET["error"]==2) {
echo "<p>Some fields were missing. Please press the "Back" button on your browser and fill in all fields marked with *</p>";
}
?>[/php]

We’re interested in error == 1.

I created 2 variables containing the content from the form, using preg_replace to prepare one formatted for email, the other as html. Then the little used &body= attribute gets the email message. I display what they’ve submitted as another fallback in case there is a formatting issue with the email link, it allows visitors to copy the content into an email message.

Credit where credit is due, the following links helped me with this:
http://stackoverflow.com/questions/1517102/replace-newlines-with-br-tags-but-only-inside-pre-tags
http://stackoverflow.com/questions/703601/posting-variables-in-php