PHP Development Board php divider

User Options
Register--Login--Top 20 Posters--Search Topics


Forum Main>>Tutorials>>Basic HTML newsletter with PHP/MYSQL

New Topic-Reply




Author
Post
Chipmunk

Rank:Settler of Bobland
Group: Head Administrator
Posts: 2867
IP Logged

PM ID and RPS ID: 1
PM [Chipmunk]

View Member Photo

Last replied to on Mon Dec 12, 2011 01:31:01
Edit Post|Quote
This tutorial will teach you how to make a simple newsletter in PHP/MYSQL with account activation. This will require PHP that is not running in SAFE_MODE or PHP that at least allows the sendmail function(duh, you can't send mail without this enabled).
First you need a table for your subscribers. So for this tutorial, we will call this table email_table. This table needs the following fields:

1. userID - Autogenerated, prmary auto-increment
2. email - varchar 255 length
3. validated - Int with a default value of Zero
4. validkey - varchar 255

So basically the signup process will Consist of three files:

connect.php - The connector file
signup.php - Actual signup file
validate.php - a file for users to validate themselves

The connector file is just a basic connect file:

Code:

$db = mysql_connect("localhost", "username", "password") or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("databse_name",$db))
die("No database selected.");
if(!get_magic_quotes_gpc())
{
$_GET = array_map('mysql_real_escape_string', $_GET);
$_POST = array_map('mysql_real_escape_string', $_POST);
$_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);
}
else
{
$_GET = array_map('stripslashes', $_GET);
$_POST = array_map('stripslashes', $_POST);
$_COOKIE = array_map('stripslashes', $_COOKIE);
$_GET = array_map('mysql_real_escape_string', $_GET);
$_POST = array_map('mysql_real_escape_string', $_POST);
$_COOKIE = array_map('mysql_real_escape_string', $_COOKIE);
}

$adminmail="you@yourdomain.com";
$path="http://www.domain.com/path";

Your username, password, and database name should go where indicated.
The $adminmail is your administrator mail, this is where you are sending the mail from.
$path is the domain and path this script is installed in. array_map and mysql_real_escape_string parses out possible SQL injections.


The signup file should look something like this:

Code:

include "connect.php";
if(isset($_POST['submit'])) //if submit was pushed
{
$email=$_POST['email'];
$checkdups="SELECT * from email_table where email='$email'";
$checkdups2=mysql_query($checkdups) or die("Could not check duplicates");
$checkdups3=mysql_num_rows($checkdups2);
if(strlen($email)<4 || substr_count($email," ")>0)
{
print "That is not a valid email address. Please try again.";
}
else if($checkdups3>0)
{
print "That email is already in our database.";
}
else
{
srand((double)microtime()*1000000); //sets random seed
$string = md5(rand(0,1000000));
$thekey=$string;
$insertemail="INSERT into email_table (email,validkey) values('$email','$thekey')";
mysql_query($insertemail) or die("Could not insert mail");
mail($email,"Thanks for signing up","Thanks, please activate your account at $path/validate.php?email=$email&string=$string","From: $adminmail");
print "You have signed up for the newsletter and a validation link has been sent to your email.";

}
}
else
{
print "<form action='signup.php' method='post'>";
print "Email:<br>";
print "<input type='text' name='email' size='20'><br>";
print "<input type='submit' name='submit' value='submit'></form>";

}



When you first go to this file, it prints a simple form asking for the e-mail to subscribe, when you hit enter if goes to the

Code:
 
if(isset($_POST['submit']))


code. First it checks to see if your email is already in the list of emails with $checkdups. Basically it queries the mysql table for that email and
then counts the number of rows, if the number of rows is greater than zero, then it will give you the message that the email is already in the database.
It also counts the number of characters in the email with strlen() and uses substr_count to check for spaces. If the email has spaces or is less than 4 characters, it returns an invalid e-mail error.

If everything goes through error checking then it first sets a random generator seed and then generates a random key validation value. It then
inserts this value into the database along with the email that subscribed. It also uses the mail() function to send a validation email to the email that
just subscribed, to make sure that person actually subscribed.

Now we have to write the validation file, validate.php:

Code:

include "connect.php";
$email=$_GET['email'];
$string=$_GET['string'];
$email=trim($email); //trims whitespace
$email=strip_tags($email); //strips out possible HTML
$string=trim($string);
$string=strip_tags($string);
$query="update email_table set validated='1' where email='$email' and validkey='$string'";
mysql_query($query) or die("Could not validate user");
print "User validated.";


So this file is short and simple it first gets the values from the strings passed in by the URL and uses trim() to trim out any whitespace and strip_tags to
kill any possible HTML injections. These can be done on one line, but for the purposes of this being a tutorial, they are shown line-by-line.
Then after it sanitizes the strings, it updates the sql table and sets the validated value to one where email and validation key are the ones passed in.


Okay the below files go into a password protected admin folder. For this I am assuming you have the ability in your control panel to password protect folders.
If not please visit This link to see how to set up a password protected directory in .htaccess.

So in the admin folder we will have 3 files:

sendletter.php -- the file that sends the newsletter
displaylist - file that displays the list of emails
deluser - delete a email

First lets go over displaylist.php:

Code:

include "../connect.php";
$getlist="SELECT * from email_table order by email ASC"; //select e-mails in ABC order
$getlist2=mysql_query($getlist) or die("Could not get list");
print "<table border='1'><tr><td>Email</td><td>Delete</td></tr>";
while($getlist3=mysql_fetch_array($getlist2))
{
print "<tr><td><A href='mailto:$getlist3[email]'>$getlist3[email]</a></td><td><A href='deluser.php?ID=$getlist3[userID]'>Delete</a></td></tr>";
}
print "</table>";




This is pretty basic, the query selects all emails on the list and displays them in alphabetical order in tabular format. You can click on the email link
to email that person directly or click on delete to delete that person from your list.

Now lets look at deluser.php , the file that actually deletes the user:

Code:

include "../connect.php";
if(isset($_POST['submit']))
{
$ID=$_POST['ID'];
$ID=trim($ID);
$ID=strip_tags($ID);
$deluser="Delete from email_table where userID='$ID'";
mysql_query($deluser) or die("Could not delete user");
print "Email deleted.";

}
else
{
$ID=$_GET['ID'];
$ID=trim($ID);
$ID=strip_tags($ID);
print "<form action='deluser.php' method='post'>";
print "<input type='hidden' name='ID' value='$ID'>";
print "Are you sure you want to delete this user?";
print "<input type='submit' name='submit' value='submit'></form>";

}


First this file prints a form asking you for a confirmation that you want to delete the user. It takes the ID passed in by the URL and sanitizes it
by trimming the whitespace and stripping any HTML tags from it. Then it hides the ID in a hidden field. When you hit submit, it sends the ID
and the query deletes the user with that ID.

Now lets look at the file that actually sends the newsletter, sendletter.php:

Code:

include "../connect.php";
if(isset($_POST['submit']))
{
$subject=$_POST['subject'];
$nletter=$_POST['nletter'];
if(strlen($subject)<1)
{
print "You did not enter a subject.";
}
else if(strlen($nletter)<1)
{
print "You did not enter a message.";
}
else
{
$nletter=$_POST['nletter'];
$subject=$_POST['subject'];
$nletter=stripslashes($nletter);
$subject=stripslashes($subject);
$lists=$_POST['lists'];
$nletter=str_replace("rn","<br>",$nletter);
//the block above formats the letter so it will send correctly.
$getlist="SELECT * from email_table order by email ASC"; //select e-mails in ABC order
$getlist2=mysql_query($getlist) or die("Could not get list");
while($getlist3=mysql_fetch_array($getlist2))
{
$headers = "From: $adminmail \r\n";
$headers.= "Content-Type: text/html; charset=ISO-8859-1 "; //send HTML enabled mail
$headers .= "MIME-Version: 1.0 ";
mail("$getlist3[email]","$subject","$nletter",$headers);
}
print "Newsletter Sent.";
}
}
else
{
print "<form action='sendletter.php' method='post'>";
print "Subject:<br>";
print "<input type='text' name='subject' size='20'><br>";
print "Message:<br>";
print "<textarea name='nletter' cols='50' rows='6'></textarea><br>";
print "<input type='submit' name='submit' value='submit'></form>";


}


Ok so that sends the newsletter. First it prints out the form with a subject and a message field.
After you hit submit it first checks if those fields are greater than 1 character in length, if they are not, it returns an error message.
If they are, then it takes the subject and the message and does some formatting using stripslashes() which, well strips the slashes from the message(some servers will put slashes in to prevent injections). Then it replaces the "rn" character with <br> or an HTML line break. Then it makes the headers, which specify where this message is from, the text/html content type makes sure that it is sending HTML email Mime version 1.0 .
Last of all it queries the list and loops through all the email address and sends the message to them all.

Thats your basic email list!


-----------------------------
Chipmunk,
Supreme Administrator

davidk20
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 14087
[PM davidk20]

RPS score: 0
RPS challenge

Posted at Mon Nov 12, 2007 08:38:25
Edit post|Quote

Need help,


When i try making the database i keep getting error messages, i dont supose any 1 could give me the SQL for it so i can just run the script?


cheers, Dave



frodo6695
Rank:acorn
Group: members
Posts: 3
IP Logged
PM ID and RPS ID: 13147
[PM frodo6695]

Posted at Mon Jan 14, 2008 19:30:16
Edit post|Quote
delete, sory, posted in wrong topic

Eric777
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 15254
[PM Eric777]

RPS score: 0
RPS challenge

Posted at Wed Feb 20, 2008 07:42:55
Edit post|Quote
Hi, Chipmunk:I'm new to php and I've been studying for a long time.Your tutorial in this newsletter was so far the easiest to understand for beginners like me.I appreciate it a lot.But can you pls. make a code that subscribers to this email can Un-Subscribe.They can click on a link in their email to unsubscribe or what have you?Thanks a lot!Enjoying learning from you:Eric

gavinmertes
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 15584
[PM gavinmertes]

RPS score: 0
RPS challenge

Posted at Thu Mar 27, 2008 07:37:17
Edit post|Quote

I keep getting the error "Could not check duplicates"


don't know what to do with line "   $checkdups2=mysql_query($checkdups) or die("Could not check duplicates");"



Yamthief
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 16590
[PM Yamthief]

RPS score: 0
RPS challenge

Posted at Thu Jul 03, 2008 08:28:30
Edit post|Quote
nice script, thanks for your useful code!

choppa
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 21003
[PM choppa]

RPS score: 0
RPS challenge

Posted at Mon Mar 16, 2009 01:31:16
Edit post|Quote

Hi Chipmunk


Thanks for this script. It's been really useful, and easy to understand. One thing I did find though - and I don't know if anyone has noticed this - is that when you send a bulk mailing list newsletter, the letter also goes to un-validated recipients in the database. I managed to fix this by adding a where validated='1' statement in this line on the sendletter.php page:


$getlist="SELECT * from email_table order by email ASC";


So it now looks like this:


$getlist="SELECT * from email_table where validated='1' order by email ASC";


As I'm new to PHP, I'm not sure if that was the correct way to put it, but it does work...



kmc
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 21873
[PM kmc]

Posted at Wed Apr 15, 2009 18:45:38
Edit post|Quote
Is there a way to send the userID along with the newletter message. I would like something like this:Newsletter blah blah blah -> then at the bottom is "If you wish to unsubscribe to our newsletter, please click here: www.domainname.com/deluser.php?userID=$userID"Then the user can delete themself. is there a way to get $userID from the database?

Update. I can get www.domainname.com/deluser.php?userID=5 , but I can't get it to do an array.

VisualRealm
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 23236
[PM VisualRealm]

RPS score: 0
RPS challenge

Posted at Sun Jun 28, 2009 11:41:44
Edit post|Quote
Did  anyone figure out the could not check duplicates?  I am very new to PHP and have been trying to teach myself how to do it.  I thought I had everything set up correct but cant get past the "could not check duplicates".  Dont know exactly where that could be wrong, mysql, path, etc.  Any response would be appreciated.  Or if someone has all the files for download.

waynsonray
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 24688
[PM waynsonray]

RPS score: 0
RPS challenge

Posted at Thu Oct 08, 2009 10:57:02
Edit post|Quote
PHP primarily acts as a filter,[32] taking input from a file or stream containing text and/or PHP instructions and outputs another stream of data; most commonly the output will be HTML. Since PHP 4, the PHP parser compiles input to produce bytecode for processing by the Zend Engine, giving improved performance over its interpreter predecessor.Originally designed to create dynamic web pages, PHP now focuses mainly on server-side scripting, and it is similar to other server-side scripting languages that provide dynamic content from a web server to a client, such as Microsoft's Active Server Pages, Sun Microsystems' JavaServer Pages, and mod_perl. PHP has also attracted the development of many frameworks that provide building blocks and a design structure to promote rapid application development (RAD). Some of these include CakePHP, Symfony, CodeIgniter, and Zend Framework, offering features similar to other web application frameworks.The LAMP and WAMP architectures have become popular in the web industry as a way of deploying web applications. PHP is commonly used as the P in this bundle alongside Linux, Apache and MySQL, although the P may also refer to Python or Perl.As of April 2007, over 20 million Internet domains were hosted on servers with PHP installed, and mod_php was recorded as the most popular Apache module. Significant websites are written in PHP including the user-facing portion of Facebook, Wikipedia (MediaWiki), Yahoo!, MyYearbook, Digg, Joomla, WordPress, YouTube, Drupal and Tagged.
-----------------------------
new york flights - national car rental - travel

stewart
Rank:acorn
Group: members
Posts: 1
IP Logged
PM ID and RPS ID: 27237
[PM stewart]

RPS score: 0
RPS challenge

Posted at Sat Feb 20, 2010 06:19:35
Edit post|Quote
I like this script - very clear and understandable! Works well.Is there any simple way to modify this script to send HTML emails?There are mass-mailers avaiable with this feature but they are too complex for my needs, as I want to draw email addresses from an existing MySQL DB in the simplest possible way. 

alice
Rank:squirreling
Group: members
Posts: 52
IP Logged
PM ID and RPS ID: 30842
[PM alice]

RPS score: 0
RPS challenge

Posted at Thu Jul 15, 2010 02:31:52
Edit post|Quote




The way how you tried to explain some
posts at here seems to me different...there are certainly different posts at
here,but i didnt find any post related to projects like
HP0-S18 , HP0-S19...if someone have information about
it,do tell me!Well any updates related to this post?if yes than do tell
me!actually i came here while surfing net to get data related to projects of
HP0-J33 and find this post different one...Is
there anyone having information about
HP0-P20 ?if yes than do tell me!Any updates?





danie53595
Rank:acorn
Group: members
Posts: 4
IP Logged
PM ID and RPS ID: 32053
[PM danie53595]

RPS score: 0
RPS challenge

Posted at Tue Aug 24, 2010 05:17:49
Edit post|Quote
One who dont know about it before may get useful information from this post , This one seems to me different type of post......well i wanna say that The way how u tried to explain some posts at here seems to me different N10-004 there are certainly different posts at here,but i didnt find any post related to projects like 70-290 .if someone have information about it,do tell me!Well any updates related to this post?if yes than do tell me!actually i came here while surfing net to get data related to projects of 70-662 and find this post different one...Is there anyone having information about EX0-101 if yes than do tell me!...any updates?if yes than do tell me!

alice
Rank:squirreling
Group: members
Posts: 52
IP Logged
PM ID and RPS ID: 30842
[PM alice]

RPS score: 0
RPS challenge

Posted at Sat Sep 25, 2010 02:22:30
Edit post|Quote
what in which you track your current member referred some new member to
join your site or purchase your product.pass4sure HP0-D07 You give some reward for it.
Making or better say coding your affiliate system is easy. Benefit of
own script is you can customize it as per your need.We will use cookies
and MySql database to track affiliates.pass4sure 350-018Why cookies not directly storing
in some variable ?pass4sure 642-825 If we store in cookie the referrer code will stay in
user browser till he/she clears cookie, but if we use PHP variable and
if page changes or registration fails the affiliate won�t get
counted.//here we are starting new session then we are checking whether
the new comer is referred by someone else before this or not, if not
then store the referrer name in session�s variable named referral, we
are getting referral code as get.pass4sure 640-816<br>

alice
Rank:squirreling
Group: members
Posts: 52
IP Logged
PM ID and RPS ID: 30842
[PM alice]

RPS score: 0
RPS challenge

Posted at Tue Sep 28, 2010 02:12:31
Edit post|Quote
Since its listing the categories in tree format with mySQL categories,
this tutorial is no really relevant if you don't already have a
populated mySQL table of categories/sub-categories.

Alternativey if you don't want that error to appear when a table is
unpopulated. You could check if mysql_num_rows($sql) is zero or not and
only run mysql_data_seek if its not zero.

Note on the tutorial:security+
I've only gotten it to work as a dropdown list. I
doesn't quite function right if you try to printing it out otherwise.citrix exam // E20-501 // comptia a+

clark40
Rank:acorn
Group: members
Posts: 17
IP Logged
PM ID and RPS ID: 35758
[PM clark40]

RPS score: 0
RPS challenge

Posted at Wed Nov 24, 2010 00:56:43
Edit post|Quote
A key feature of shell scripts is that the invocation of their interpreters are handled as a core operating system 220-701 feature. So rather than a user's shell only being able to execute scripts in that shell's language, or a script only having its interpreter directive handled correctly if it was run from a shell 642-832 (both of which were limitations in the early Bourne shell's handling of scripts), shell scripts are set up and executed by the OS itself. A modern shell script is not just on the same footing as system commands, but rather many system CISSP commands are actually shell scripts (or more generally, scripts, since some of them are not interpreted by a shell, but instead by Perl, Python, or some other language). This extends to returning exit codes like other system utilities to indicate success or failure, and allows them to be 350-030 called as components of larger programs regardless of how those larger tools are implemented.

clark40
Rank:acorn
Group: members
Posts: 17
IP Logged
PM ID and RPS ID: 35758
[PM clark40]

RPS score: 0
RPS challenge

Posted at Sat Jan 01, 2011 06:12:59
Edit post|Quote
To make FULLTEXT MATCH work with Japanese UTF-8 text, be careful that
words from your Japanese text be N10-004 dumps separated by the __ASCII__ space
character, not Japanese UTF-8 (or other) spacing characters.<br>(when
using 70-680 dumps phpMyAdmin to manage data/ write a SY0-201 dumps SQL query, you must switch away
from your Japanese IME to insert a space VCP-410 dumps char...)

kristina.matt
Rank:acorn
Group: members
Posts: 8
IP Logged
PM ID and RPS ID: 43189
[PM kristina.matt]

RPS score: 0
RPS challenge

Posted at Tue Mar 29, 2011 00:48:50
Edit post|Quote
Quote:
  

Need help,


When i try making the database i keep getting error messages, i dont supose any 1 could give me the SQL for it so i can just run the script?


cheers, Dave

I really enjoyed this post and will be referencing it in discount perfume our courses.
Lots of our students are cameras | discount furniture interested in taking their sites to the next
level with PHP and jQuery


Thanks,

Go Seeq Search Engines



kristina.matt
Rank:acorn
Group: members
Posts: 8
IP Logged
PM ID and RPS ID: 43189
[PM kristina.matt]

RPS score: 0
RPS challenge

Posted at Fri Apr 08, 2011 01:26:35
Edit post|Quote

It’s a awesome list. I’m a web developer and Noupe has always been my
first choice


Thanks for sharing

cheap electronics | men's health | men's health | men's health



brian2011
Rank:squirreling
Group: members
Posts: 108
IP Logged
PM ID and RPS ID: 42823
[PM brian2011]

RPS score: 0
RPS challenge

Posted at Thu Jun 02, 2011 01:49:46
Edit post|Quote
bar stoolsbar chairsbar tableleather sofafloor jackhydraulic jackjack standsjack standhydraulic jackshydraulic bottle jackBase capbooster cablesbooster cablebattery cabledress bag shelf hanging organizer non-woven fabricglass bottledust maskdust maskssProtective maskProtective masksMedical maskbamboo furniturebamboo kitchenbamboo flooringreclinersectional sofabottle jackair jackshop pressbushing brass bushingdigital thermometerclinical thermometerear thermometerdigital blood pressure monitorshop craneChimney hoodspower stripChristmas Lampglue gunWell SocketBattery clipBooster cablesCar wash brushClothes hangersElectric socketPower boardPower cablePower cordPower socketPower stripsRatchet strapsRatchet tiedowmSolar lightingSoldering irons
-----------------------------
i come from china

brian2011
Rank:squirreling
Group: members
Posts: 108
IP Logged
PM ID and RPS ID: 42823
[PM brian2011]

RPS score: 0
RPS challenge

Posted at Tue Jun 14, 2011 01:51:51
Edit post|Quote
crystal vasecandle holderscrystal ornamentscrystal figurinescrystal giftcrystal blockbar stoolsbadminton racketPVC windows aluminum windowspower meterplastic frameplastic filmcolor filmpvc film table clothLamp holderLamp basebulb holderauto lamp baseLamp socketCooker hoodsExhaust hoodsVent hoodsIsland hoodStainless steel hoodsGlass hoodshower enclosurebathtubshower roompower cablespeaker cableleisure chairshopping bagnon woven bagstorage boxLamp holderLamp baseBrass holdersLamp capsdry bushingplain bearingsolar collectorsolar water heateroutdoor furniturerattan furnituresolar water heatersolar collectordinning chairsdinning chairsolar energysolar water heater solar collectorsbooster cablesbattery cliptow roperatchet tie dowmMedical masksgas maskgas masksmedical face masksasbestos dust maskextension cordglue gunpower socketbamboo skewerbamboo kitchenbamboo spoonbamboo polesbamboo craftsbamboo tablewarebamboo box
-----------------------------
i come from china

Page: 1 2  >>   Last



Powered by © Chipmunk Board

Flash games Ninja games-Web Design New York