PHP Email Verification is a secure system for verifying email addresses through opt-in forms. It sends verification emails with unique tokens that users click to confirm their email addresses.
- Email verification with cryptographically secure tokens
- User registration with name and email capture
- IP address logging for security auditing
- CSRF Protection: Token-based protection against Cross-Site Request Forgery attacks
- XSS Prevention: Comprehensive output escaping and Content Security Policy headers
- SQL Injection Prevention: Parameterized queries using PDO prepared statements
- Bot Protection: Google ReCaptcha v2 integration
- Secure Token Generation: 256-bit cryptographically secure tokens using
random_bytes() - Security Headers: Complete set of security headers (CSP, X-Frame-Options, HSTS, etc.)
- No Sequential ID Exposure: Verification uses only secure tokens, preventing user enumeration
- Environment Variable Management: Sensitive data stored securely via PHP dotenv
- Secure Email Delivery: SMTP authentication support using PHPMailer
- Error Handling: Safe error messages that don't expose system information
- Install dependencies with composer:
composer install - Register for ReCaptcha sitekey and secret
- Create a MySQL/MariaDB database
- Copy .env.example to .env, and fill required values:
cp .env.example .env - Configure your web server to point to the project directory
- Ensure PHP 7.4+ is installed with PDO MySQL extension
Required variables in .env:
DB_HOST,DB_NAME,DB_USER,DB_PASS- Database connectionURL- Your site's base URL (e.g., https://example.com)RECAPTCHA_SITEKEY,RECAPTCHA_SECRET- ReCaptcha credentialsEMAIL_HOST,EMAIL_FROM,EMAIL_FROM_NAME- Email configurationEMAIL_SUBJECT,EMAIL_BODY- Email contentSMTP_AUTH- Set to 'true' if using SMTP authentication
Optional SMTP variables (when SMTP_AUTH=true):
SMTP_SECURE- Encryption type ('tls' or 'ssl')SMTP_USERNAME,SMTP_PASSWORD- SMTP credentials
Optional security variables:
APP_ENV- Set to 'development' to see detailed errors (use 'production' in live environments)
php-email-verification/
├── submit.php # Registration form and submission handler
├── verify.php # Email verification handler
├── db.php # Database connection and schema
├── error_handler.php # Error handling utilities
├── csrf_protection.php # CSRF token management
├── security_headers.php # Security headers configuration
├── uuid_generator.php # UUID generation utilities
├── .env.example # Environment variables template
└── composer.json # PHP dependencies
While this project includes many security features, rate limiting is not implemented and should be added before production deployment. Consider these approaches:
- Database-based throttling:
// Example: Track submission attempts
function checkRateLimit($ip, $maxAttempts = 5, $window = 300) {
// Store attempt timestamps in database
// Check if IP exceeded maxAttempts in last $window seconds
// Return true if allowed, false if rate limited
}- Redis/Memcached-based limiting:
// Example using Redis
$key = "rate_limit:register:" . $ip;
$attempts = $redis->incr($key);
if ($attempts === 1) {
$redis->expire($key, 300); // 5 minute window
}
return $attempts <= 5;- Session-based limiting (less secure, easily bypassed):
$_SESSION['attempts'] = ($_SESSION['attempts'] ?? 0) + 1;
$_SESSION['first_attempt'] = $_SESSION['first_attempt'] ?? time();-
Web Server Configuration:
- Nginx: Use
limit_req_zoneandlimit_reqdirectives - Apache: Use
mod_ratelimitormod_evasive
- Nginx: Use
-
CDN/WAF Solutions:
- Cloudflare Rate Limiting
- AWS WAF rate-based rules
- Fastly rate limiting
-
Fail2ban Integration:
- Monitor application logs for failed attempts
- Automatically ban IPs at firewall level
-
Registration endpoint (
submit.php):- 5 attempts per IP per 15 minutes
- 20 attempts per IP per hour
- 100 attempts per IP per day
-
Verification endpoint (
verify.php):- 10 attempts per IP per 5 minutes
- 50 attempts per IP per hour
-
Consider implementing:
- Progressive delays (exponential backoff)
- CAPTCHA challenges after threshold
- Account lockouts for repeated failures
- Email notification for suspicious activity
- HTTPS Only: Always use HTTPS in production
- Database Security:
- Use least-privilege database user
- Consider database connection pooling
- Regular backups
- Monitoring:
- Log all registration attempts
- Monitor for unusual patterns
- Set up alerts for high failure rates
- Token Expiration: Consider adding expiration times to verification tokens
- Email Security:
- Implement SPF, DKIM, and DMARC
- Monitor email bounce rates
- Handle email delivery failures gracefully
- Input Validation: Add additional email format validation
- Password Protection: If extending to full authentication, use
password_hash()andpassword_verify()
The system automatically creates a users table with:
id: Internal auto-incrementing ID (not exposed)email: User's email addressname: User's namevalidated: Boolean verification statustoken: Unique verification token (indexed)ipaddress: Registration IP address
Dependencies are managed by Composer:
- PHP 7.4+ with PDO MySQL extension
- MySQL/MariaDB database
- PHPMailer - Email sending
- ReCaptcha - Bot protection
- PHP dotenv - Environment management
Before deployment:
- Test with invalid tokens to ensure proper error handling
- Verify CSRF protection by attempting cross-origin submissions
- Check email delivery to various providers
- Test ReCaptcha with both success and failure cases
- Verify all security headers are properly set
- Test with development mode off to ensure errors aren't exposed
- Fork this repo
- Create a feature branch
- Commit your changes
- Push to the branch
- Create a pull request
For issues, questions, or suggestions, please create an issue on GitHub.