Email subscriptions are a common feature on websites, allowing users to receive newsletters, updates, or promotions directly in their inbox. In this tutorial, we’ll walk you through how to implement an email subscription system using PHP—from setting up the database to sending confirmation emails.
Start by creating a database table to store user email addresses and subscription timestamps. Here’s a sample SQL command to create the table:
CREATE TABLE subscribers ( id INT PRIMARY KEY AUTO_INCREMENT, email VARCHAR(255) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Next, add a simple HTML form to your webpage to collect users’ email addresses:
<form action="subscribe.php" method="post"> <input type="email" name="email" placeholder="Enter your email address" required> <button type="submit">Subscribe</button> </form>
Create a PHP script (e.g., subscribe.php) to process the form submission. This script will:
<?php // Connect to the database $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_database"; $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Database connection failed: " . $conn->connect_error); } // Get the submitted email address $email = $_POST['email']; // Validate email format if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { die("Please enter a valid email address"); } // Check for existing subscription $sql = "SELECT id FROM subscribers WHERE email='$email'"; $result = $conn->query($sql); if ($result->num_rows > 0) { die("You have already subscribed to our notifications"); } // Insert the new subscription $sql = "INSERT INTO subscribers (email) VALUES ('$email')"; if ($conn->query($sql) === TRUE) { echo "Subscription successful!"; } else { echo "Subscription failed: " . $conn->error; } $conn->close(); ?>
After a successful subscription, you can use PHP’s mail() function to send a confirmation message to the user:
// Send confirmation email $to = $email; $subject = "Welcome to our Newsletter"; $message = "Thank you for subscribing to our news updates!"; $headers = "From: your_email@example.com"; mail($to, $subject, $message, $headers);
Be sure to replace the example email address with your actual sending email to ensure delivery.
By following the steps in this tutorial, you can quickly implement a basic yet functional email subscription system using PHP. It’s a practical way to build engagement and maintain communication with your site visitors. For better reliability, consider integrating a professional SMTP service in production environments.