blob: 320a8015c73465128140044395f12ccbfe8cddda (
plain)
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
|
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Sanitize input
$name = htmlspecialchars(strip_tags(trim($_POST["name"] ?? '')));
$email = htmlspecialchars(strip_tags(trim($_POST["email"] ?? '')));
$message = htmlspecialchars(strip_tags(trim($_POST["message"] ?? '')));
$recaptchaResponse = $_POST['g-recaptcha-response'] ?? '';
// Validate input
if (empty($name) || empty($email) || empty($message) || empty($recaptchaResponse)) {
die("All fields are required, including reCAPTCHA.");
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format.");
}
// Verify reCAPTCHA
$secretKey = getenv("RECAPTCHA_SECRET_KEY"); // Use environment variable for security
$recaptchaURL = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$recaptchaResponse";
$response = file_get_contents($recaptchaURL);
$responseKeys = json_decode($response, true);
if (!$responseKeys["success"]) {
die("reCAPTCHA verification failed. Please try again.");
}
// Send email via PHPMailer
$mail = new PHPMailer(true);
try {
// SMTP Configuration (Use Environment Variables for Security)
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = getenv("SMTP_EMAIL"); // Get email from environment variable
$mail->Password = getenv("SMTP_PASSWORD"); // Get password from environment variable
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Set email details
$mail->setFrom($email, $name);
$mail->addAddress(getenv("RECEIVER_EMAIL")); // Receiver's email
$mail->Subject = "New Contact Form Submission from $name";
$mail->Body = "From: $name <$email>\n\n$message";
// Send email
$mail->send();
echo "Message sent successfully!";
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
?>
|