你会更好地使用换行符而不是逗号:
if ($_POST['subscribe'])) {
touch('emails.txt');
$emails = file('emails.txt', FILE_IGNORE_NEW_LINES);
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
&& !in_array($_POST['email'], $emails)) {
$emails[] = $_POST['email'];
file_put_contents('emails.txt', explode("\n", $emails));
}
} elseif ($_POST['unsubscribe']) {
touch('emails.txt');
$emails = file('emails.txt', FILE_IGNORE_NEW_LINES);
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
&& ($index = array_search($_POST['email'], $emails)) !== false) {
unset($emails[$index]);
file_put_contents('emails.txt', explode("\n", $emails));
}
}
确保在站点根目录之外保护您的emails.txt文件。
您可能希望为此使用 SQLite 数据库:
$db = new PDO('sqlite:emails.sqlite');
$db->exec('CREATE TABLE IF NOT EXISTS subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email VARCHAR(64) NOT NULL UNIQUE
)');
if ($_POST['subscribe']) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$stmt = $db->prepare('INSERT ON CONFLICT IGNORE subscriptions (email) VALUES (:email)');
$stmt->bindValue(':email', $_POST['email']);
$stmt->execute();
}
} elseif ($_POST['unsubscribe']) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$stmt = $db->prepare('DELETE FROM subscriptions WHERE email = :email');
$stmt->bindValue(':email', $_POST['email']);
$stmt->execute();
}
}
它没有经过测试,但应该可以工作。确保还在站点根目录之外保护您的emails.sqlite 。