-
Notifications
You must be signed in to change notification settings - Fork 13
/
AjaxForm.php
166 lines (146 loc) · 5.14 KB
/
AjaxForm.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
<?php
/**
* Basic, simple and secure bootstrap contact form.
*
* @see https://github.com/raspgot/AjaxForm-PHPMailer-reCAPTCHA
* @package PHPMailer | reCAPTCHA v3
* @author Gauthier Witkowski <contact@raspgot.fr>
* @link https://raspgot.fr
* @version 1.3.1
*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
# https://www.php.net/manual/fr/timezones.php
date_default_timezone_set('America/Los_Angeles');
require __DIR__ . '/vendor/PHPMailer/Exception.php';
require __DIR__ . '/vendor/PHPMailer/PHPMailer.php';
require __DIR__ . '/vendor/PHPMailer/SMTP.php';
require __DIR__ . '/vendor/recaptcha/autoload.php';
# Constants to redefined
# Check this for more configurations: https://blog.mailtrap.io/phpmailer
const HOST = ''; # SMTP server
const USERNAME = ''; # SMTP username
const PASSWORD = ''; # SMTP password
const SECRET_KEY = ''; # GOOGLE secret key
const SMTP_SECURE = PHPMailer::ENCRYPTION_STARTTLS; # or ENCRYPTION_SMTPS
const SMTP_AUTH = true;
const PORT = 587;
const SUBJECT = 'New message !';
const HANDLER_MSG = [
'success' => '✔️ Your message has been sent !',
'token-error' => '❌ Error recaptcha token.',
'enter_name' => '❌ Please enter your name.',
'enter_email' => '❌ Please enter a valid email.',
'enter_message' => '❌ Please enter your message.',
'ajax_only' => '❌ Asynchronous anonymous.',
# Mail body
'email_body' => '
<h1>{{subject}}</h1>
<p><b>Date</b>: {{date}}</p>
<p><b>Name</b>: {{name}}</p>
<p><b>E-Mail</b>: {{email}}</p>
<p><b>Message</b>: {{message}}</p>
<p><b>IP</b>: {{ip}}</p>
'
];
# Check if request is Ajax request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
statusHandler(true, HANDLER_MSG['ajax_only']);
}
# Check if fields has been entered and valid
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = secure($_POST['name']) ?? statusHandler(true, HANDLER_MSG['enter_name']);
$email = filter_var(secure($_POST['email']), FILTER_SANITIZE_EMAIL) ?? statusHandler(true, HANDLER_MSG['enter_email']);
$message = secure($_POST['message']) ?? statusHandler(true, HANDLER_MSG['enter_message']);
$token = secure($_POST['recaptcha-token']) ?? statusHandler(true, HANDLER_MSG['token-error']);
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'];
$date = new DateTime();
}
# Prepare email body
$email_body = HANDLER_MSG['email_body'];
$email_body = template($email_body, [
'subject' => SUBJECT,
'date' => $date->format('j/m/Y H:i:s'),
'name' => $name,
'email' => $email,
'ip' => filter_var($ip, FILTER_VALIDATE_IP),
'message' => $message
]);
# Verifying the user's response
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY);
$resp = $recaptcha
->setExpectedHostname($_SERVER['SERVER_NAME'])
->verify($token, filter_var($ip, FILTER_VALIDATE_IP));
if ($resp->isSuccess()) {
# Instanciation of PHPMailer
$mail = new PHPMailer(true);
$mail->setLanguage('en', __DIR__ . '/vendor/PHPMailer/language/');
try {
# Server settings
$mail->SMTPDebug = SMTP::DEBUG_OFF; # Enable verbose debug output
$mail->isSMTP(); # Set mailer to use SMTP
$mail->Host = HOST; # Specify main and backup SMTP servers
$mail->Port = PORT; # TCP port
$mail->SMTPAuth = SMTP_AUTH; # Enable SMTP authentication
$mail->Username = USERNAME; # SMTP username
$mail->Password = PASSWORD; # SMTP password
$mail->SMTPSecure = SMTP_SECURE; # Enable TLS encryption, `ssl` also accepted
# Recipients
$mail->setFrom(USERNAME, 'Raspgot');
$mail->addAddress($email, $name);
$mail->AddCC(USERNAME, 'Dev_copy');
$mail->addReplyTo(USERNAME, 'Information');
# Content
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = SUBJECT;
$mail->Body = $email_body;
$mail->AltBody = strip_tags($email_body);
# Send email
$mail->send();
statusHandler(false, HANDLER_MSG['success']);
} catch (Exception $e) {
statusHandler(true, $mail->ErrorInfo);
}
} else {
statusHandler(true, $resp->getErrorCodes());
}
/**
* Template string values
* @param string $string
* @param array $vars
* @return string
*/
function template(string $string, array $vars): string
{
foreach ($vars as $name => $val) {
$string = str_replace("{{{$name}}}", $val, $string);
}
return $string;
}
/**
* Secure inputs fields
* @param string $post
* @return string
*/
function secure(string $post): string
{
$post = htmlspecialchars($post, ENT_QUOTES);
$post = stripslashes($post);
$post = trim($post);
return $post;
}
/**
* Error or success message
* @param bool $error
* @param mixed $message
* @return string
*/
function statusHandler(bool $error, $message): string
{
die(json_encode([
'error' => $error,
'message' => $message
]));
}