我運行一個小網站,我的用戶請求我設置一個郵件列表。我發現了一個簡單的免費腳本,將電子郵件地址受保護的文本文件,email.txt
,CSV格式:PHP腳本從逗號分隔列表中刪除電子郵件地址
[email protected],[email protected],blah,blah,blah
腳本完美的作品。但是,當用戶取消列表訂閱時,通過文件手動刪除電子郵件地址是一件麻煩事。我需要創建一個簡單的腳本來刪除電子郵件地址。
我只想要一個簡單的PHP腳本,顯示一個文本框,以便用戶可以輸入他們的電子郵件地址,然後單擊「取消通訊」按鈕。該腳本應該搜索文本文件,找到給定的電子郵件地址並將其刪除,並刪除它的尾部逗號。
例如,說的email.txt
內容是
[email protected],[email protected],[email protected]
如果鍵入「[email protected]」成我想要的腳本中顯示的文本框,我想這個文件,看起來像這樣:
[email protected],[email protected]
更新:我想這個代碼:
<?php
function showForm() {
echo '
<form method="post" action="">
Email Address: <input type="text" name="email"> <br />
<input type="submit" value="Cancel Newsletter" name="submit">
</form>
';
}
$_POST['email']
$to_delete = 'email';
$file = array_flip(explode(",",file_get_contents("email.txt")));
unset($file[$to_delete]);
file_put_contents("email.txt",implode(",",array_flip($file));
if(!$file_put_contents) {
die('Error occured');
} else {
echo 'Your subscription has been cancelled. You will not receive any further emails from us.';
}
}
} else {
showForm();
}
?>
此代碼甚至不顯示窗體。
更新2:
的另一種嘗試。在寫這個劇本:
<?php
$email = $_POST["email"];
$text = file_get_contents("email.txt");
$oldWord = "$email";
$newWord = "";
$text = str_replace($oldWord , $newWord , $text);
$fp = fopen('email.txt', 'w');
fwrite($fp, $text);
fclose($file);
?>
這工作就去掉了E-mail地址去,但沒有公佈(回波)。我想根據腳本是否成功地在列表中找到$email
並刪除它,說出「該電子郵件未訂閱」或「您已被刪除」。
更新3 2011年12月31日:
我嘗試了先進的代碼和剛得到一個空白頁,所以我又回到我的版本。這裏是我現在的代碼:
<html>
<body>
<form method="post" action="">
<p>Email Address: <input type="text" name="email"></p>
<input type="submit" value="Cancel Newsletter" name="submit">
</form>
<?php
$email = $_POST["email"];
$basetext = file_get_contents("email.txt");
$oldWord = "$email";
$newWord = "";
$text = str_replace($oldWord , $newWord , $basetext);
$str1 = $basetext;
// echo strlen($str1);
$str2 = $text;
// echo strlen($str2);
$fp = fopen('email.txt', 'w');
fwrite($fp, $text);
if ($str1 > $str2) { // This part handles the success/fail message
echo ("Success!");
} else {
echo ("Fail!");
}
fclose($file);
?>
</body>
</html>
這很好用。但是,它在加載頁面時顯示「失敗」消息,而不是在觸發加載時按下提交按鈕後顯示。
如果可能,我想保留原始代碼,只需重新排列,以便它只顯示「成功!」或「失敗!」一旦它執行了代碼。
我想echo消息是頁面上執行的最後一個腳本。
[PHPList(http://www.phplist.com/) – hakre 2011-12-30 16:14:21
它看起來像你應該有一個解析器錯誤的'$ _POST ['email']'行。 – 2011-12-30 20:32:14
你會如何建議我編碼,以消除錯誤?感謝隊友 – 2011-12-30 20:45:03