I am new to PHP and have been doing some reading and searching to try and get this correct, but I am running short on time to get it working properly. It is not quite finished for I still have to enter the code to email the people when they subscribe or unsubscribe. The problems I am having are:
1) getting the unsubscribe to work properly
2) keeping the "Thank you for joining" from showing up in the other messages
3) getting rid of the extra character at the end of the email address in the .txt file
4) making sure that when people unsubscribe they are removed form the .txt file.
If there is anything else that missed please let me know. The code below is what I currently have and the display messages and file locations are generic for testing purposes. Some of the code I have written myself and some of it I have gotten from reading various posts and tutorials. This is for a form that is on a website for users to subscribe/unsubscribe their email address for a newsletter. I have gotten the subscribe to work and it will write to a file.
------Form----- this is only in its basic form to test with
<html>
<head>
<title>Sign up for Newsletter</title>
</head>
<body bgcolor="white" text="black" link="blue" vlink="purple" alink="red">
<form action="subscribe.php" method=post>
<center>Your Email Address: <input type=text name="address" size=37></center>
<center><input type=radio name=action value=subscribe checked> Subscribe <input type=radio name=action value=unsubscribe> Unsubscribe </center>
<center><input type="submit" value="Submit"></center></form>
</body>
</html>
------PHP script-----
<?php
$subscribe = $_GET['subscribe'];
$unsubscribe = $_GET['unsubscribe'];
$address = $_POST['address'];
if ($subscribe = "subscribe")
{
if (ereg('^[a-zA-Z0-9 \._\-]+@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]+$', $address))
{
echo ("<HTML><BODY>Thank you for joining.</BODY></HTML>");
}
else
{
echo ("<HTML><BODY><b>$address</b> not a valid email address. Please try again.</BODY></HTML>");
}
if(file_exists("email_list.txt"))
{
$newfile = fopen("email_list.txt", "r");
while(!feof($newfile))
{
$duplicate = fgetss($newfile, 255);
if(eregi("$address", $duplicate))
{
echo ("<HTML><BODY><b>$address</b> is already in the database.</BODY></HTML>");
fclose($newfile);
exit;
}
}
fclose($newfile);
$addemail = fopen("email_list.txt", "a");
fputs($addemail, "$address\n");
fclose($addemail);
}
else
{
$newfile = fopen("email_list.txt", "a");
fputs($newfile, "$address\n");
fclose($newfile);
}
if ($unsubscribe = "unsubscribe")
{
$emails = file("email_list.txt");
for($index = 0; $index < count($emails); $index++)
{
if(ereg("$unsubscribe", $emails[$index]))
{
$emails[$index] = "";
$thefile = fopen("email_list.txt", "w");
for($newindex = 0; $newindex <count($emails); $newindex++)
{
if($emails[$newindex] != "")
{
fputs($thefile, "$emails[$newindex]");
}
}
fclose($thefile);
echo("<HTML><BODY><b>$address</b> has successfully been removed from the database.</BODY></HTML>");
}
}
}
}
?>