File Manager V1.5
FILE_CONTENT: secure_send_mail.php
<?php
/**
* Secure Contact Form Handler
* Replaces vulnerable send_mail.php with secure implementation
*/
require_once 'security/security_middleware.php';
require_once 'secure_db_conn.php';
// Initialize security middleware
$security = new SecurityMiddleware();
// Rate limiting for form submissions
$rateLimiter = new RateLimiter();
$ip = $_SERVER['REMOTE_ADDR'];
if (!$rateLimiter->checkLimit($ip, MAX_FORM_SUBMISSIONS_PER_HOUR, 3600)) {
http_response_code(429);
die(json_encode(['error' => 'Too many form submissions. Please try again later.']));
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
die(json_encode(['error' => 'Method not allowed']));
}
// CSRF Protection
if (!SecurityMiddleware::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
http_response_code(403);
die(json_encode(['error' => 'Invalid security token']));
}
try {
// Validate required fields
$requiredFields = ['name', 'email', 'phone', 'subject', 'message'];
$errors = [];
foreach ($requiredFields as $field) {
if (empty($_POST[$field])) {
$errors[] = "Field '$field' is required";
}
}
if (!empty($errors)) {
throw new Exception('Validation failed: ' . implode(', ', $errors));
}
// Sanitize and validate input
$name = SecurityMiddleware::sanitizeInput($_POST['name'], 'string');
$email = SecurityMiddleware::sanitizeInput($_POST['email'], 'email');
$phone = SecurityMiddleware::sanitizeInput($_POST['phone'], 'string');
$subject = SecurityMiddleware::sanitizeInput($_POST['subject'], 'string');
$message = SecurityMiddleware::sanitizeInput($_POST['message'], 'string');
// Additional validation
if (!SecurityMiddleware::validateInput($email, 'email')) {
throw new Exception('Invalid email address');
}
if (!SecurityMiddleware::validateInput($phone, 'phone')) {
throw new Exception('Invalid phone number');
}
if (!SecurityMiddleware::validateInput($name, 'string', ['min_length' => 2, 'max_length' => 100])) {
throw new Exception('Invalid name');
}
if (!SecurityMiddleware::validateInput($subject, 'string', ['min_length' => 5, 'max_length' => 200])) {
throw new Exception('Invalid subject');
}
if (!SecurityMiddleware::validateInput($message, 'string', ['min_length' => 10, 'max_length' => 2000])) {
throw new Exception('Invalid message');
}
// Get client information
$clientIP = $_SERVER['REMOTE_ADDR'];
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
// Store in database
$db = SecureDatabase::getInstance();
$contactData = [
'name' => $name,
'email' => $email,
'phone' => $phone,
'subject' => $subject,
'message' => $message,
'ip_address' => $clientIP,
'user_agent' => $userAgent
];
$contactId = $db->insert('contact_submissions', $contactData);
// Send email notification
$emailSent = sendSecureEmail($name, $email, $phone, $subject, $message);
// Send SMS notification (if enabled and configured)
$smsSent = false;
if (defined('SMS_ENABLED') && SMS_ENABLED) {
$smsSent = sendSecureSMS($phone, $name);
}
// Log successful submission
$logger = new SecurityLogger();
$logger->log('INFO', 'Contact form submitted successfully', [
'contact_id' => $contactId,
'email' => $email,
'email_sent' => $emailSent,
'sms_sent' => $smsSent
]);
// Return success response
$response = [
'success' => true,
'message' => 'Thank you for contacting us. We will be in touch with you very soon.',
'contact_id' => $contactId
];
header('Content-Type: application/json');
echo json_encode($response);
} catch (Exception $e) {
// Log error
$logger = new SecurityLogger();
$logger->log('ERROR', 'Contact form submission failed: ' . $e->getMessage(), [
'ip' => $_SERVER['REMOTE_ADDR'],
'post_data' => array_keys($_POST) // Log field names only, not values
]);
http_response_code(400);
echo json_encode(['error' => 'Form submission failed. Please try again.']);
}
/**
* Send secure email notification
*/
function sendSecureEmail($name, $email, $phone, $subject, $message) {
try {
$to = 'info@ke-techno.com';
$emailSubject = 'Customer Inquiry - ' . htmlspecialchars($subject);
// Create email body
$emailBody = "New customer inquiry received:\n\n";
$emailBody .= "Name: " . htmlspecialchars($name) . "\n";
$emailBody .= "Email: " . htmlspecialchars($email) . "\n";
$emailBody .= "Phone: " . htmlspecialchars($phone) . "\n";
$emailBody .= "Subject: " . htmlspecialchars($subject) . "\n";
$emailBody .= "Message:\n" . htmlspecialchars($message) . "\n\n";
$emailBody .= "Submitted: " . date('Y-m-d H:i:s') . "\n";
$emailBody .= "IP Address: " . $_SERVER['REMOTE_ADDR'] . "\n";
// Set headers
$headers = [
'From: noreply@ke-techno.com',
'Reply-To: ' . $email,
'X-Mailer: PHP/' . phpversion(),
'Content-Type: text/plain; charset=UTF-8',
'X-Priority: 3'
];
return mail($to, $emailSubject, $emailBody, implode("\r\n", $headers));
} catch (Exception $e) {
error_log('Email sending failed: ' . $e->getMessage());
return false;
}
}
/**
* Send secure SMS notification (placeholder - implement with your SMS provider)
*/
function sendSecureSMS($phone, $name) {
try {
// This is a placeholder - implement with your preferred SMS provider
// Remove hardcoded credentials and use environment variables
$message = "Thank you " . htmlspecialchars($name) . " for contacting KE-Technologies. We will be in touch with you shortly. For more info call us on 0779400095 / 0759653156";
// Format phone number
$phone = preg_replace('/^0/', '256', $phone);
$phone = preg_replace('/[^0-9]/', '', $phone);
// SMS API implementation would go here
// For security, use environment variables for API credentials
// Example:
// $apiKey = getenv('SMS_API_KEY');
// $apiSecret = getenv('SMS_API_SECRET');
// Log SMS attempt
$logger = new SecurityLogger();
$logger->log('INFO', 'SMS notification attempted', [
'phone' => substr($phone, 0, 3) . '***' . substr($phone, -2), // Masked phone
'name' => $name
]);
return true; // Return true for now, implement actual SMS sending
} catch (Exception $e) {
error_log('SMS sending failed: ' . $e->getMessage());
return false;
}
}
?>
[ KEMBALI ]