Skip to content

Instantly share code, notes, and snippets.

@jameswilson
Forked from frjo/contact.php
Last active March 7, 2022 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameswilson/3fbb21c0669de2c7a29720e6d7aa88c7 to your computer and use it in GitHub Desktop.
Save jameswilson/3fbb21c0669de2c7a29720e6d7aa88c7 to your computer and use it in GitHub Desktop.
PHP script for contact form
.contact-form input:not(:placeholder-shown):valid,
.contact-form textarea:not(:placeholder-shown):valid {
background-color: #f4feee;
}
.contact-form input:not(:placeholder-shown):invalid,
.contact-form textarea:not(:placeholder-shown):invalid {
background-color: #fff0f0;
}
.contact-form label,
.contact-form button {
display: block;
}
.js-submitted input:valid,
.js-submitted textarea:valid {
background-color: #f4feee;
}
.js-submitted input:invalid,
.js-submitted textarea:invalid {
background-color: #fff0f0;
}
.hidden {
display: none;
}
(function ($) {
("use strict");
// Remove the "no javascript" messages
$(".contact-no-js").detach();
// Contact form.
$(".contact-form").each(function () {
var $contact_form = $(this);
var $contact_button = $contact_form.find(".form-submit");
var contact_action = "/assets/php/contact.php";
// Display the hidden form.
$contact_form.removeClass("hidden");
// Wait for a mouse to move, indicating they are human.
$("body").mousemove(function () {
// Unlock the form.
$contact_form.attr("action", contact_action);
$contact_button.attr("disabled", false);
});
// Wait for a touch move event, indicating that they are human.
$("body").on("touchmove", function () {
// Unlock the form.
$contact_form.attr("action", contact_action);
$contact_button.attr("disabled", false);
});
// A tab or enter key pressed can also indicate they are human.
$("body").keydown(function (e) {
if (e.keyCode === 9 || e.keyCode === 13) {
// Unlock the form.
$contact_form.attr("action", contact_action);
$contact_button.attr("disabled", false);
}
});
// Mark the form as submitted.
$contact_button.click(function () {
$contact_form.addClass("js-submitted");
});
// Display messages.
if (location.search.substring(1) !== "") {
switch (location.search.substring(1)) {
case "submitted":
$(".contact-submitted").removeClass("hidden");
break;
case "error":
$(".contact-error").removeClass("hidden");
break;
}
}
});
})(jQuery);
<p class="contact-no-js messages messages--error">You must have Javascript enabled to use this contact form.</p>
<p class="contact-submitted messages messages--status hidden">Your message was sent.</p>
<p class="contact-error messages messages--error hidden">There was an error sending the message.</p>
<form class="contact-form hidden" action="#" method="post" accept-charset="UTF-8">
<div class="form-item">
<label for="edit-name">
Your Name
<span class="form-required" title="This field is required.">*</span>
</label>
<input type="text" id="edit-name" name="name" placeholder="Your name" tabindex="1" required autofocus>
</div>
<div class="form-item">
<label for="edit-mail">
Your e-mail address
<span class="form-required" title="This field is required.">*</span>
</label>
<input type="email" class="form-text" id="edit-mail" name="email" placeholder="Your e-mail address" tabindex="2" required>
</div>
<div class="form-item">
<input type="text" id="edit-url" class="hidden" name="url" placeholder="Skip if you are a human">
</div>
<div class="form-item">
<label for="edit-name">
Telephone
<span class="form-required" title="This field is required.">*</span>
</label>
<input type="text" id="edit-phone" name="phone" placeholder="Your phone" tabindex="3" required>
</div>
<div class="form-item">
<label for="edit-message">
Message
<span class="form-required" title="This field is required.">*</span>
</label>
<textarea id="edit-message" name="message" rows="5" placeholder="Please tell us about your travel dates and how many people are traveling." tabindex="5" required></textarea>
</div>
<div class="form-actions">
<button type="submit" name="submit" class="form-submit" disabled>Send message</button>
</div>
</form>
<?php
/**
* Working spam-free php email script for Dreamhost.
* https://gist.github.com/jameswilson/3fbb21c0669de2c7a29720e6d7aa88c7
* Adapted from https://gist.github.com/frjo/23e45ec5e690d90f6bfcaca06873fd73
* https://codepen.io/frjo/pen/pwWoEd/
* https://xdeb.org/post/2017/a-html5-php-javascript-contact-form-with-spam-protection/
*/
// Set the e-mail address that submission should be sent to.
$to = 'info@example.com';
// Optionally, add a blind carbon copy, set to false or empty string to disable.
$bcc = 'another@example.com';
// Set the sender/return path header to your Dreamhost server account to avoid
// sending errors.
$sender = 'Example.com <useraccount@servername.dreamhost.com>';
// Set the e-mail subject prefix.
$prefix = 'Website feedback';
// DO NOT EDIT ANYTHING BELOW UNLESS YOU KNOW WHAT YOU ARE DOING.
$error = false;
$success = false;
// Check that referer is local server.
if (!isset($_SERVER['HTTP_REFERER']) || (parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) != $_SERVER['SERVER_NAME'])) {
exit('Direct access not permitted');
}
// Get the URL that submitted the form.
$contact_form_url = strtok($_SERVER['HTTP_REFERER'], '?');
// Check that this is a post request.
if ($_SERVER['REQUEST_METHOD'] != 'POST' || empty($_POST)) {
$error = true;
}
// Check if fake url field is filled in, i.e. spam bot.
if (!empty($_POST['url'])) {
$error = true;
}
// Check that e-mail address is valid.
if ((bool) filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL)) {
$email = trim($_POST['email']);
} else {
$error = true;
}
if (!$error) {
// Construct the mail with headers.
$name = _contact_clean_str($_POST['name'], ENT_QUOTES, true, true);
$prefix = _contact_clean_str($prefix, ENT_NOQUOTES, true, true);
$phone = _contact_clean_str($_POST['phone'], ENT_NOQUOTES, true, true);
$subject = "[$prefix] Message from $name";
$message = _contact_clean_str($_POST['message'], ENT_NOQUOTES);
$lines = explode("\n", $message);
array_walk($lines, '_contact_ff_wrap');
$message = "Dear admin, $name sent you the following message:\n\n-----\n\n";
$message .= implode("\n", $lines) . "\n\n-----\n\n";
$message .= "Email: $email\n";
$message .= "Phone: $phone\n";
$message .= "Submitted via: $contact_form_url\n";
$headers = [
'From' => $sender,
'Sender' => $sender,
'Return-Path' => $sender,
'Reply-To' => "$name <$email>",
'MIME-Version' => '1.0',
'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
'Content-Transfer-Encoding' => '8Bit',
'X-Mailer' => 'PHP Mail',
];
if ($bcc) {
$headers["Bcc"] = $bcc;
}
$mime_headers = [];
foreach ($headers as $key => $value) {
$mime_headers[] = "$key: $value";
}
$mail_headers = join("\n", $mime_headers);
// Send the mail, suppressing errors and setting Return-Path with the "-f" option.
$success = @mail($to, $subject, $message, $mail_headers, '-f' . $sender);
}
$status = $success ? 'submitted' : 'error';
// Redirect back to contact form with status.
header('Location: ' . $contact_form_url . '?' . $status, TRUE, 302);
exit;
function _contact_ff_wrap(&$line) {
$line = wordwrap($line, 72, " \n");
}
function _contact_clean_str($str, $quotes, $strip = false, $encode = false) {
if ($strip) {
$str = strip_tags($str);
}
$str = htmlspecialchars(trim($str), $quotes, 'UTF-8');
if ($encode && preg_match('/[^\x20-\x7E]/', $str)) {
$str = '=?UTF-8?B?' . base64_encode($str) . '?=';
}
return $str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment