How can PHP be utilized to automate email notifications based on specific dates, such as birthdays?
To automate email notifications for birthdays using PHP, you can create a script that checks the current date against a list of birthdays stored in a database. If a match is found, an email can be sent to notify the person of their upcoming birthday.
<?php
// Connect to database and retrieve list of birthdays
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT email FROM birthdays WHERE DATE_FORMAT(birthdate, '%m-%d') = DATE_FORMAT(NOW(), '%m-%d')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$to = $row["email"];
$subject = "Birthday Reminder";
$message = "Happy Birthday!";
$headers = "From: birthday@example.com";
mail($to, $subject, $message, $headers);
}
} else {
echo "No birthdays today.";
}
$conn->close();
?>