如何编写PHP双重加入订阅表格

hyp*_*not 5 php mysql email md5

我正在尝试编写一个小的PHP脚本来管理邮件列表的订阅。我试图找到可以在互联网上找到的任何资源,但我只想到了:

  1. 非常简单的PHP脚本,仅具有单选择加入或“伪”双重选择加入功能。
  2. 非常复杂的多MB PHP项目,例如PHPList(7.8 MB!)

通过“伪造”双重选择加入,我调用了一些方法,这些方法要么将电子邮件地址作为验证字符串,要么使用浏览器中的cookie。

我想要实现的是:

  1. 有人可以用PHP形式写它的电子邮件地址,然后单击“提交”。
  2. 他收到一封电子邮件,其中包含需要单击的URL。链接不应包含电子邮件地址,而应包含md5或随机字符串
  3. 点击该网址后,他进入显示“已确认电子邮件”的页面

在服务器端,地址可以保存在受保护文件夹的文本文件中,或者如果您认为将它们保存在数据库中然后再保存在数据库中确实很重要。

到目前为止,我的问题是:

  1. 有人可以指导我一些有关如何编写此类脚本的教程或文章
  2. 我应该使用数据库还是简单文件。我需要做的只是插入几行新电子邮件,并可以进行重复检查。
  3. 如何存储双重选择加入系统的临时ID。我考虑过使用类似的方法md5 ("email" . "passphrase")来生成ID,并将其存储在电子邮件地址旁边。

cod*_*gar 5

只是为了好玩,这里有一个非常深入的例子。应该很容易掌握那里发生了什么以及为什么。

警告:代码尚未经过测试,因此可能存在语法和其他错误。

<?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>
  ';

}
Run Code Online (Sandbox Code Playgroud)