Just for fun, here is a pretty simple example. It should be easy to understand what is happening there and why.
Caution: the code has not been tested, so syntax and other errors are possible.
<?php // Salt for hashing confirmation keys $salt = 'yoursecretstring12#11;.-_.21'; $url = 'http://www.yoursite.tld/thisscript.php'; $fromEmail = ' you@yoursite.tld '; $dbHost = 'localhost'; $dbUser = 'dbuser'; $dbPass = 'dbpass'; $dbDatabase = 'dbname'; mysql_connect($dbHost, $dbUser, $dbPass); mysql_select_db($dbDatabase); $ip = $_SERVER["REMOTE_ADDR"]; if ( isset( $_GET['key'] ) && isset( $_GET['email'] ) ) { // If we have 'email' and 'key' parameters, we are handling an opt-in click $email = mysql_real_escape_string( $_GET['email'] ); // Check if key matches hash of email and salt combination and if email is really an email if ( sha1( $email.$salt ) == $_GET['key'] && filter_var($email, FILTER_VALIDATE_EMAIL) ) { // Check if entry already exists $checkDupes = mysql_query( "SELECT COUNT(*) as cnt FROM emails WHERE email = '$email'"; ); $result = mysql_fetch_assoc($checkDupes); if ($result['cnt'] < 1) { // Fresh email, insert into db along with remote ip and timestamp mysql_query( "INSERT INTO emails (email, ip, timestamp) VALUES ( '$email', $ip, NOW() );" ); die('Subscription confirmed!'); } else { die('Email already exists in database'); } } else { die('Key mismatch or invalid email!'); } } else if ( isset( $_POST['email'] ) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) { // Form submission, send confirmation email $email = $_POST['email']; $key = sha1( $email.$salt ); $link = $url . '?email=' . $email . '&key=' . $key; $mailSubject = 'Please confirm your subscription'; $mailTo = $email; $mailBody = 'Please confirm your subscription by clicking <a href="$link">this link</a>'; $headers = 'From: ' . $fromEmail . "\r\n"; mail( $mailTo, $mailSubject, $mailBody ); } else { // Present form and show error if needed if ( isset( $_POST['email'] ) ) { echo "Ivalid email submitted!<br />"; } echo ' <form method="post" action="'.$url.'"> Email: <input type="text" name="email" /><br /> <input type="submit" value="Submit" /> </form> '; }
source share