Last active
April 13, 2021 23:14
-
-
Save hayatbiralem/bb633dbf25a7d7c42e943058f70b47a8 to your computer and use it in GitHub Desktop.
Email PHP and jQuery Ajax Scripts for Webflow HTML Export with Google Recaptcha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
var Webflow = window.Webflow || []; | |
Webflow.push(function () { | |
// === Custom Form Handling === | |
// unbind webflow form handling | |
$(document).off('submit'); | |
// new form handling | |
$(document).on('submit', '#wf-form-Contact-Form', function (e) { | |
e.preventDefault(); | |
var $form = $(this); | |
var $submit = $form.find('input[type="submit"]'); | |
var submitVal = $submit.val(); | |
var submitWait = $submit.data('wait'); | |
$submit.val(submitWait).prop('disabled', true); | |
var $successMessage = $('.success-message').hide(); | |
var $errorMessage = $('.error-message').hide(); | |
var url = $form.attr('action'); | |
$.ajax({ | |
type: "POST", | |
url: url, | |
data: $form.serialize(), // serializes the form's elements. | |
success: function (data) { | |
console.log(data); // show response from the php script. | |
$form.hide(); | |
$successMessage.show(); | |
}, | |
error: function () { | |
$errorMessage.show(); | |
}, | |
complete: function () { | |
$submit.val(submitVal).prop('disabled', false); | |
} | |
}); | |
}); | |
}); | |
})(jQuery); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Import PHPMailer classes into the global namespace | |
//These must be at the top of your script, not inside a function | |
use PHPMailer\PHPMailer\PHPMailer; | |
use PHPMailer\PHPMailer\Exception; | |
//Load | |
require 'PHPMailer/src/Exception.php'; | |
require 'PHPMailer/src/PHPMailer.php'; | |
require 'PHPMailer/src/SMTP.php'; | |
/** | |
* @source https://gist.github.com/james2doyle/33794328675a6c88edd6 | |
*/ | |
function json_response($code = 200, $message = null) | |
{ | |
// clear the old headers | |
header_remove(); | |
// set the actual code | |
http_response_code($code); | |
// set the header to make sure cache is forced | |
header("Cache-Control: no-transform,public,max-age=300,s-maxage=900"); | |
// treat this as json | |
header('Content-Type: application/json; charset=utf-8'); | |
$status = array( | |
200 => '200 OK', | |
400 => '400 Bad Request', | |
422 => 'Unprocessable Entity', | |
500 => '500 Internal Server Error' | |
); | |
// ok, validation error, or failure | |
header('Status: ' . $status[$code]); | |
// return the encoded json | |
return json_encode(array( | |
'status' => $code < 300, // success or not? | |
'message' => $message | |
)); | |
} | |
/** | |
* @source https://gist.github.com/jonathanstark/dfb30bdfb522318fc819 | |
*/ | |
function verify_recaptcha() | |
{ | |
// for Cloudflare | |
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) { | |
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"]; | |
} | |
$post_data = http_build_query( | |
array( | |
'secret' => RECAPTCHA_SECRET, | |
'response' => $_POST['g-recaptcha-response'], | |
'remoteip' => $_SERVER['REMOTE_ADDR'] | |
) | |
); | |
$opts = array( | |
'http' => | |
array( | |
'method' => 'POST', | |
'header' => 'Content-type: application/x-www-form-urlencoded', | |
'content' => $post_data | |
) | |
); | |
$context = stream_context_create($opts); | |
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context); | |
$result = json_decode($response); | |
return $result->success; | |
} | |
if (!verify_recaptcha()) { | |
echo json_response(422); | |
die; | |
} | |
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { | |
echo json_response(422); | |
die; | |
} | |
$first_name = trim($_POST['First-Name']); | |
$last_name = trim($_POST['Last-Name']); | |
$email = trim($_POST['Email']); | |
$phone = $_POST['Contact-Phone-Number']; | |
$message = trim($_POST['Message']); | |
$empty = 'Unspecified'; | |
$rows = [ | |
'Name' => "{$first_name} {$last_name}", | |
'Email' => $email, | |
'Phone' => empty($phone) ? $empty : $phone, | |
'Message' => empty($message) ? $empty : $message, | |
]; | |
$message = []; | |
$message[] = '<table>'; | |
$message[] = '<tbody>'; | |
foreach ($rows as $label => $value) { | |
$message[] = '<tr>'; | |
$message[] = "<th align=\"left\" style=\"padding: 8px;\">{$label}</th>"; | |
$message[] = "<td align=\"left\" style=\"padding: 8px;\">:</td>"; | |
$message[] = "<td align=\"left\" style=\"padding: 8px;\">{$value}</td>"; | |
$message[] = '</tr>'; | |
} | |
$message[] = '</tbody>'; | |
$message[] = '</table>'; | |
$message = implode("", $message); | |
$subject = "{$first_name} {$last_name} isimli göndericiden mesaj var"; | |
if (in_array('', [$first_name, $last_name, $email]) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { | |
echo json_response(422); | |
die; | |
} | |
//Instantiation and passing `true` enables exceptions | |
$mail = new PHPMailer(true); | |
try { | |
//Server settings | |
// $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output | |
$mail->isSMTP(); //Send using SMTP | |
$mail->Host = SMTP_HOST; //Set the SMTP server to send through | |
$mail->SMTPAuth = SMTP_AUTH; //Enable SMTP authentication | |
$mail->Username = SMTP_USERNAME; //SMTP username | |
$mail->Password = SMTP_PASSWORD; //SMTP password | |
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged | |
$mail->Port = SMTP_PORT; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above | |
//Recipients | |
$mail->setFrom(SMTP_USERNAME, FROM_NAME); | |
$mail->addAddress(TO, NAME); //Add a recipient | |
// $mail->addAddress('[email protected]'); //Name is optional | |
$mail->addReplyTo($email); | |
// $mail->addCC('[email protected]'); | |
// $mail->addBCC('[email protected]'); | |
//Attachments | |
// $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments | |
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name | |
//Content | |
$mail->isHTML(true); //Set email format to HTML | |
$mail->Subject = $subject; | |
$mail->Body = $message; | |
$mail->AltBody = strip_tags($message); | |
$mail->send(); | |
echo json_response(200); | |
} catch (Exception $e) { | |
echo json_response(400, $mail->ErrorInfo); | |
} | |
die; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment