Skip to content

Instantly share code, notes, and snippets.

@krystyna93
Created June 13, 2023 07:27
Show Gist options
  • Save krystyna93/c1ba31eebdbdf4e44272dff440614315 to your computer and use it in GitHub Desktop.
Save krystyna93/c1ba31eebdbdf4e44272dff440614315 to your computer and use it in GitHub Desktop.
Custom WordPress Contact Form
<?php
function display_encrypted_contact_form() {
// Initialize variables
$errors = array();
$success = false;
// Check if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate nonce
$nonce = $_POST['contact-form-nonce'];
if (!wp_verify_nonce($nonce, 'contact-form')) {
$errors[] = "Nonce verification failed. Please try again.";
}
// Get and sanitize form data
$name = trim(sanitize_text_field($_POST["name"]));
$email = filter_var(trim(sanitize_email($_POST["email"])), FILTER_SANITIZE_EMAIL);
$message = trim(sanitize_textarea_field($_POST["message"]));
$math_answer = intval($_POST["math-answer"]);
$hidden_field = sanitize_text_field($_POST["hidden"]);
// Validate form data
if (empty($name) || empty($email) || empty($message) || empty($math_answer)) {
$errors[] = "Please fill in all required fields.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email address.";
}
// Verify math answer
$math_question = "What is 2 + 2?";
if ($math_answer != 4) {
$errors[] = "Incorrect math answer. Please try again.";
}
// Check for hidden field value (to prevent spam bots)
if (!empty($hidden_field)) {
$errors[] = "Hidden field was filled in. This may be spam.";
}
// If there are no errors, send the email
if (empty($errors)) {
// Set up encryption parameters
$method = 'AES-256-CBC';
$key = 'your_secret_key_here';
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);
// Encrypt the message using OpenSSL
$encrypted_message = openssl_encrypt($message, $method, $key, OPENSSL_RAW_DATA, $iv);
// Build the email message with the encrypted message
$to = "your_email_address_here";
$subject = "New contact form submission";
$body = "Name: {$name}\nEmail: {$email}\nMessage: " . base64_encode($encrypted_message);
$headers = "From: {$email}\r\nReply-To: {$email}\r\n" .
"Content-Type: text/plain; charset=UTF-8\r\n" .
"Content-Transfer-Encoding: base64\r\n" .
"X-Mailer: PHP/" . phpversion();
$success = mail($to, $subject, chunk_split(base64_encode($iv) . $body), $headers);
// Clear sensitive data from memory
unset($message);
unset($encrypted_message);
unset($key);
unset($iv);
if (!$success) {
$errors[] = "Error sending email.";
}
}
// Return a JSON response
header('Content-type: application/json');
echo json_encode(array(
'success' => $success,
'errors' => $errors
));
exit;
}
// Generate and store nonce
$nonce = wp_create_nonce('contact-form');
?>
<?php if ($success): ?>
<div class="success-message">
<p>Thank you for your message!</p>
</div>
<?php else: ?>
<?php if (!empty($errors)): ?>
<div class="error-message">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php
// Generate a new math question
$num1 = rand(1, 10);
$num2 = rand(1, 10);
$math_question = "What is {$num1} + {$num2}?";
?>
<form id="contact-form">
<input type="hidden" name="contact-form-nonce" value="<?php echo $nonce; ?>">
<label>Name:</label><br>
<input type="text" name="name" value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>"><br>
<label>Email address:</label><br>
<input type="email" name="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>"><br>
<label</label><br>
<textarea name="message"><?php echo isset($_POST['message']) ? $_POST['message'] : ''; ?></textarea><br>
<label>Please answer the following math question: <?php echo $math_question; ?></label><br>
<input type="number" name="math-answer"><br>
<div class="form-group">
<label for="hidden">Leave this field blank:</label>
<input type="text" name="hidden" id="hidden">
</div>
<button type="submit">Send</button>
</form>
<div id="message"></div>
<script>
var form = document.getElementById('contact-form');
var message = document.getElementById('message');
form.addEventListener('submit', function(event) {
event.preventDefault();
// Get the form data
var formData = new FormData(form);
// Make an asynchronous request to the server using AJAX
var xhr = new XMLHttpRequest();
xhr.open('POST', window.location.href);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
message.innerHTML = '<div class="success-message"><p>Thank you for your message!</p></div>';
} else {
var errorsHtml = '<div class="error-message"><ul>';
for (var i = 0; i < response.errors.length; i++) {
errorsHtml += '<li>' + response.errors[i] + '</li>';
}
errorsHtml += '</ul></div>';
message.innerHTML = errorsHtml;
}
}
};
xhr.send(formData);
});
</script>
<?php endif;
}
// Add shortcode for the encrypted contact form
add_shortcode('encrypted_contact_form', 'display_encrypted_contact_form');
-----
// instead of shortcode simply call the display_encrypted_contact_form() function wherever you want to display the form. For example, you could add it to a template file like this
<?php if (is_page('contact')): ?>
<div class="contact-form-container">
<?php display_encrypted_contact_form(); ?>
</div>
<?php endif;
-----
// You could also call the function directly from a plugin or theme file like this:
// Assuming the function is defined in a separate file called contact-form.php
require_once 'contact-form.php';
// Display the form
display_encrypted_contact_form();
// This will simply include the file that contains the function definition, and then call the function to display the form.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment