<?php
session_start();
include '../../assets/constant/config.php';
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
try {
// Normalize email input
$email = trim(strtolower($_POST['email']));
// Check if the email already exists
$st = $conn->prepare("SELECT COUNT(*) FROM subscribe WHERE email = ?");
$st->execute([$email]);
$emailExists = $st->fetchColumn();
if ($emailExists > 0) {
// Email already exists
$_SESSION['error'] = "This email is already subscribed!";
?>
<script>
alert("This email is already subscribed!");
// Redirect to the appropriate page
<?php if (!empty($_POST['page'])) { ?>
window.location.href = "../../../<?php echo htmlspecialchars($_POST['page'], ENT_QUOTES, 'UTF-8'); ?>";
<?php } else { ?>
window.location.href = "../../../index.php";
<?php } ?>
</script>
<?php
} else {
// Insert the email into the database
$stmt = $conn->prepare("INSERT INTO `subscribe`(`email`) VALUES (?)");
$stmt->execute([$email]);
$_SESSION['success'] = "Thank you for subscribing!";
?>
<script>
alert("Thank you for subscribing!");
// Redirect to the appropriate page
<?php if (!empty($_POST['page'])) { ?>
window.location.href = "../../../<?php echo htmlspecialchars($_POST['page'], ENT_QUOTES, 'UTF-8'); ?>";
<?php } else { ?>
window.location.href = "../../../index.php";
<?php } ?>
</script>
<?php
}
} catch (Exception $e) {
// Handle any potential errors
$_SESSION['error'] = "An error occurred. Please try again.";
?>
<script>
alert("An error occurred. Please try again.");
// Redirect to the appropriate page
<?php if (!empty($_POST['page'])) { ?>
window.location.href = "../../../<?php echo htmlspecialchars($_POST['page'], ENT_QUOTES, 'UTF-8'); ?>";
<?php } else { ?>
window.location.href = "../../../index.php";
<?php } ?>
</script>
<?php
}
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// Compress image function
function compressImage($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
imagejpeg($image, $destination, $quality);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
imagepng($image, $destination, round(9 - ($quality / 10))); // PNG quality ranges from 0 to 9
}
}
?>