Forms & Email

PHP Newsletter Subscription Starter

Email subscription storage starter with validation and a double-opt-in token hash.

Overview

Email subscription storage starter with validation and a double-opt-in token hash.

What this script does

This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.

Source code

<?php
declare(strict_types=1);
function addSubscriber(PDO $pdo,string $email): void {
    $email=mb_strtolower(trim($email));
    if (!filter_var($email,FILTER_VALIDATE_EMAIL)) throw new InvalidArgumentException('Invalid email.');
    $token=bin2hex(random_bytes(32)); $hash=hash('sha256',$token);
    $s=$pdo->prepare('INSERT INTO newsletter_subscribers(email,verification_token_hash,subscribed_at) VALUES(:email,:hash,NOW())');
    $s->execute(['email'=>$email,'hash'=>$hash]);
    // Email the raw token in a verification link; store only its hash.
}

Download starter source: Download PHP Newsletter Subscription Starter source

Installation and customization

  1. Review the code and required PHP extensions.
  2. Configure database and storage settings outside the public web root where applicable.
  3. Add authorization, rate limiting and logging for public-facing endpoints.
  4. Test valid, invalid and boundary inputs before deployment.

> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.