Files
portfoliowai/send_contact.php
T

77 lines
2.4 KiB
PHP

<?php
require_once __DIR__ . '/config/db.php';
// Retrieve client IP address
function getClientIp() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
return $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// In case of multiple IPs, get the first one
$ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($ipList[0]);
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header("Location: index.php");
exit();
}
$clientIp = getClientIp();
$rateLimit = intval($_ENV['RATE_LIMIT'] ?? getenv('RATE_LIMIT') ?? 10);
// Query submissions count from this IP address in the last hour
$stmt = $mysqli->prepare("SELECT COUNT(*) as count FROM email_submissions WHERE ip_address = ? AND submitted_at >= NOW() - INTERVAL 1 HOUR");
if ($stmt) {
$stmt->bind_param("s", $clientIp);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$submissionCount = $result['count'] ?? 0;
$stmt->close();
} else {
$submissionCount = 0;
}
if ($submissionCount >= $rateLimit) {
header("Location: index.php?status=error&msg=Rate limit exceeded. You can only send $rateLimit emails per hour.#contact");
exit();
}
// Log submission to database
$logStmt = $mysqli->prepare("INSERT INTO email_submissions (ip_address) VALUES (?)");
if ($logStmt) {
$logStmt->bind_param("s", $clientIp);
$logStmt->execute();
$logStmt->close();
}
// Forward submission to FormSubmit via cURL
$contactEmail = $_ENV['CONTACT_EMAIL'] ?? getenv('CONTACT_EMAIL') ?? 'crischarlesgarcia345@gmail.com';
$url = "https://formsubmit.co/" . $contactEmail;
if (!function_exists('curl_init')) {
header("Location: index.php?status=error&msg=cURL is not available on this server.#contact");
exit();
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false || $httpCode >= 400) {
header("Location: index.php?status=error&msg=Failed to send message via mail service. Please try again later.#contact");
} else {
header("Location: index.php?status=success#contact");
}
exit();
?>