PHP技术咨询:注册验证邮件发送及联系表单抄送提交者方法
Hey there! Let's tackle your two PHP email questions one by one—they're both super common (and useful) for contact/registration forms.
1. Sending a Copy/Confirmation Email to the Form Submitter
You already have code that sends submissions to your inbox, so adding a copy for the submitter just requires grabbing their email from the form and either cc'ing them or sending a separate, personalized message.
Method 1: Add a CC to Your Existing Email
This is the simplest way if you just want the submitter to get the exact same email you receive. Update your PHP code to include a CC header, and make sure to validate their email first:
// First, grab and validate the submitter's email $userEmail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); if (!$userEmail) { $errorMessage = "Please enter a valid email address."; echo $errorMessage; exit; } // Build your email headers (add the CC line here) $headers = "From: " . $from . "\r\n"; $headers .= "Reply-To: " . $userEmail . "\r\n"; $headers .= "CC: " . $userEmail . "\r\n"; // This copies the submitter $headers .= "Content-Type: text/plain; charset=UTF-8\r\n"; // Then proceed with your existing mail() call as before
Method 2: Send a Separate Confirmation Email
If you want to send a friendlier, custom message (like a thank-you note), call the mail() function a second time just for the submitter:
// First, send the email to yourself (your existing code) // ... (keep your original mail() call here) // Now send a personalized confirmation to the user $userSubject = "Thanks for reaching out!"; $userMessage = "Hi there,\n\nWe've received your submission and will get back to you as soon as possible.\n\nHere's a quick recap of what you sent:\n"; // Optional: Loop through the $fields array to include their form data foreach ($fields as $key => $label) { $userMessage .= "$label: " . $_POST[$key] . "\n"; } $userMessage .= "\nBest regards,\nYour Team"; $userHeaders = "From: " . $from . "\r\n"; $userHeaders .= "Content-Type: text/plain; charset=UTF-8\r\n"; // Send the confirmation email mail($userEmail, $userSubject, $userMessage, $userHeaders);
2. Sending a Verification Email for Registration
Email verification requires a few extra steps: generating a unique token, storing it in your database, sending a link with that token, and then validating the token when the user clicks the link.
Step 1: Set Up Your Database Table
First, create a table to store user info and verification tokens (adjust fields to match your registration data):
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE, verification_token VARCHAR(64) NOT NULL, is_verified BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, expires_at DATETIME NOT NULL -- Optional: Add to set token expiration );
Step 2: Generate & Store the Token on Registration
When a user submits their registration form, generate a unique token and save it to the database (always use prepared statements to avoid SQL injection!):
$userEmail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); if (!$userEmail) { echo "Invalid email address."; exit; } // Generate a secure, unique verification token $verificationToken = bin2hex(random_bytes(32)); // 64-character random string $expiresAt = date('Y-m-d H:i:s', strtotime('+24 hours')); // Token expires in 24h // Insert user into database $pdo = new PDO('mysql:host=YOUR_HOST;dbname=YOUR_DB', 'USERNAME', 'PASSWORD'); $stmt = $pdo->prepare("INSERT INTO users (email, verification_token, expires_at) VALUES (?, ?, ?)"); $stmt->execute([$userEmail, $verificationToken, $expiresAt]);
Step 3: Send the Verification Email
Create an email with a link that includes the token:
$verificationLink = "https://yourwebsite.com/verify.php?token=" . $verificationToken; $subject = "Please Verify Your Email"; $message = "Hi,\n\nThanks for registering! Click the link below to verify your email:\n" . $verificationLink . "\n\nThis link will expire in 24 hours.\n\nIf you didn't register, you can safely ignore this email.\n\nBest regards,\nYour Team"; $headers = "From: " . $from . "\r\n"; $headers .= "Content-Type: text/plain; charset=UTF-8\r\n"; mail($userEmail, $subject, $message, $headers);
Step 4: Create the Verification Page (verify.php)
When the user clicks the link, validate the token and mark their email as verified:
if (isset($_GET['token'])) { $token = $_GET['token']; $pdo = new PDO('mysql:host=YOUR_HOST;dbname=YOUR_DB', 'USERNAME', 'PASSWORD'); // Check if the token exists, is valid, and hasn't expired $stmt = $pdo->prepare("SELECT id FROM users WHERE verification_token = ? AND is_verified = FALSE AND expires_at > NOW()"); $stmt->execute([$token]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if ($user) { // Mark the user as verified and clear the token $updateStmt = $pdo->prepare("UPDATE users SET is_verified = TRUE, verification_token = NULL WHERE id = ?"); $updateStmt->execute([$user['id']]); echo "Success! Your email has been verified."; } else { echo "Invalid or expired verification token."; } } else { echo "No verification token provided."; }
内容的提问来源于stack exchange,提问作者Bodan Flavio

