我正在尝试编写一个小的 PHP 脚本来管理邮件列表的订阅。我试图找到我可以在互联网上找到的任何资源,但我只想到了:
- 非常简单的 PHP 脚本,仅具有单一选择加入或“虚假”双重选择加入功能。
- 非常复杂的多 MB PHP 项目,例如 PHPList(7.8 MB!)
通过“虚假”双重选择加入,我调用将电子邮件地址作为验证字符串或在浏览器中使用 cookie 的方法。
我想实现的是:
- 有人可以在 PHP 表单中写下它的电子邮件地址,然后单击提交
- 他收到一封电子邮件,其中包含他需要点击的 URL。该链接不应包含电子邮件地址,而应包含一些 md5 或随机字符串
- 点击 URL 后,他会进入一个显示“电子邮件已确认”的页面
在服务器端,地址可以保存在 protected 文件夹中的文本文件中,或者如果您认为将它们保存在数据库中真的很重要,那么就保存在数据库中。
到目前为止我的问题是:
- 有人可以指导我阅读一些关于如何编写此类脚本的教程或文章
- 我应该使用数据库还是简单的文件。我所需要的只是插入简单的几行新电子邮件,并可能进行重复检查。
- 如何存储双重选择加入系统的临时 id-s。我考虑过使用
md5 ("email". "passphrase")
之类的东西来生成 ID 并将它们存储在电子邮件地址旁边。
最佳答案
只是为了好玩,这里有一个非常深入的例子。应该很容易掌握那里发生了什么以及为什么。
警告:代码尚未经过测试,因此可能存在语法和其他错误。
<?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>
';
}
关于php - 如何编写 PHP 双重选择加入订阅表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7703200/