File size: 1,985 Bytes
628740b |
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 |
<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers, Content-Type, Access-Control-Allow-Methods, Authorization, X-Requested-With');
// Simulate database connection (replace with your actual database code)
$subscriptionsFile = '../models/Subscription.php';
// Initialize subscriptions file if it doesn't exist
if (!file_exists($subscriptionsFile)) {
file_put_contents($subscriptionsFile, json_encode([]));
}
// Get POST data
$email = $_POST['email'] ?? '';
$notification_opt_in = isset($_POST['notification_opt_in']) ? (bool)$_POST['notification_opt_in'] : false;
// Validate email
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo json_encode(['message' => 'Please provide a valid email address.']);
exit;
}
// Read existing subscriptions
$subscriptions = json_decode(file_get_contents($subscriptionsFile), true);
// Check if email already exists
foreach ($subscriptions as $sub) {
if ($sub['email'] === $email) {
http_response_code(409);
echo json_encode(['message' => 'This email is already subscribed.']);
exit;
}
}
// Add new subscription
$newSubscription = [
'email' => $email,
'notification_opt_in' => $notification_opt_in,
'subscribed_at' => date('Y-m-d H:i:s'),
'active' => true
];
$subscriptions[] = $newSubscription;
// Save subscriptions
if (file_put_contents($subscriptionsFile, json_encode($subscriptions, JSON_PRETTY_PRINT))) {
http_response_code(200);
echo json_encode(['message' => 'Successfully subscribed to our newsletter!']);
} else {
http_response_code(500);
echo json_encode(['message' => 'Subscription failed. Please try again.']);
}
exit;
?> |