Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create Newsletter subscription
#1
Welcome and Enjoy!

About:
Newsletter is a great way to inform your visitors about Updates and Realeses on your Homepage.
I will show you how to create a Newsletter subscription for your Users, with two types of storing their E-Mails, 1 = Flat file database, 2 = MySql Database.

Requirements:
  • Basic understanding of PHP and it's Syntax
  • Host/Server with enabled mail() function.
  • For the second example you'll need an MySql database access. And you need to know how to work with it.


Files:
  1. subscribe.php
  2. send.php
  3. subscribe.htm
  4. send.htm

Functions:
  1. Flat file:
  2. MySql:


HTML files:
First let us create needed html files.

subscribe.htm
Code:
<html>
    <head>
        <title>Newsletter subscribe</title>
    </head>
    <body>
        <form action="subscribe.php" method="post">
            Email: <input type="text" name="email" maxlength="255" size="35" />
            <input type="submit" name="subscribe" value="Subscribe" />
        </form>
    </body>
</html>

send.htm
Code:
<html>
    <head>
        <title>Send E-Mails</title>
    </head>
    <body>
        <form action="send.php" method="post">
            <textarea cols="65" rows="20" name="mail"></textarea><br />
            <input type="submit" name="send" value="Send" />
        </form>
    </body>
</html>

Saving E-Mails:

Flat file:
This script isn't very long and it'S easy to understand.

subscribe.php
PHP Code:
if(!isset($_POST['subscribe']) || $_POST['email'] == "") {
    die(
"Failed to submit your E-Mail!"););
}elseif(!
$handle fopen("newsletter.txt""a+")) {
    die(
"Failed to open newsletter.txt");

In the first "if" block we check if "$_POST['subscribe']" was set. $_POST['subscribe'] is set when the user press Subscribe button in subscribe.htm, and we also check if "$_POST['email']" isn't empty.
In the second if block (elseif) we try to open newsletter.txt with the function "fopen" and if the file can not be opened or created we will output an error and let the script end with the "die" function.

PHP Code:
$mail $_POST['email']."
"
;

fwrite($handle$mail);
fclose($handle); 
Now we define "$mail" as the value wich the user has written in the input field in subscribe.htm
With "fwrite" we write the "$mail" into newly opened/created file "$handle"

MySql:


First you will need a database table, I've named mine "mails".
Code:
CREATE TABLE `mails` (
`id` SMALLINT( 6 ) UNSIGNED NOT NULL AUTO_INCREMENT ,
`mail` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL ,
PRIMARY KEY ( `id` ) ,
INDEX ( `id` )
) ENGINE = MYISAM

subscribe.php
PHP Code:
$db = array(
    
'host' => 'localhost',
    
'user' => 'root',
    
'pass' => '',
    
'base' => 'newsletter'
);

if(
$connect mysql_connect($db['host'], $db['user'], $db['pass'])) {
    
$select mysql_select_db($db['base']);
}else{
    die(
"Connection failed!");

This is used to connect to and select your database.
I will skip this since you can read more here .
http://www.supportforums.net/showthread.php?tid=116
Thanks to MyNameIs

PHP Code:
if(!isset($_POST['subscribe']) || $_POST['email'] == "") {
    die(
"Failed to submit your E-Mail!");
}

$sql 'INSERT INTO `mails` (`id` ,`mail`) VALUES (NULL , \''.$_POST['email'].'\');';

if(!
$query mysql_query($sql)) {
    die(
"Could not save your E-Mail!");
}

mysql_close($connect); 

We set out mysql command to "$sql" variable.
Then with mysql_query we try to save the E-Mail to the databse, and if it fails we let the script end and output error message.

And lastly we close the connection with mysql_close()

Sending E-Mails:
Flat file:

And again we doe some chacking
PHP Code:
if(!isset($_POST['send'])) {
    die(
"Failed to submit your E-Mail!");
}elseif(!
$handle fopen("newsletter.txt""r")) {
    die(
"Unable to read newsletter.txt");

The main difference between this code and the one in subscribe.php is the mode used in fopen("newsletter.txt", "r");.
It is set to "r" wich opens the file for reading only.

Now we run a loop and send our mail to every one in the list with the mail() function
PHP Code:
while(!feof($handle)) {
    
$mail fgets($handle);
    if(!
mail($mail"Tutorial Newsletter (E-Mail subject)"$_POST['mail'], "From: your@mail.com")) {
        die(
"Unable to send mail to ".$mail);
    }
}

fclose($handle); 
This loop runs until the script reaches the file end (feof) and "!" in the front of feof means "not".
So on english "while not end of file do...".
If the mail() function fails to send the mail we output the error and let the script end.
And finally we "fclose()" the file.

MySql:
This part is explained above
PHP Code:
$db = array(
    
'host' => 'localhost',
    
'user' => 'root',
    
'pass' => '',
    
'base' => 'newsletter'
);

if(
$connect mysql_connect($db['host'], $db['user'], $db['pass'])) {
    
$select mysql_select_db($db['base']);
}else{
    die(
"Connection failed!");
}

if(!isset(
$_POST['send'])) {
    die(
"Failed to submit your E-Mail!");


Next we run a query with mysql_query("SELECT * FROM `mails`"), and if the query fails we let the script die.
PHP Code:
if(!$query mysql_query("SELECT * FROM `mails`")) {
    die(
"Query failed!");


Now the loop for mysql
PHP Code:
while($row mysql_fetch_array($query)) {
    if(!
mail($row['mail'], "Tutorial newsletter subject"$_POST['mail'], "your@mail.com")) {
        die(
"Unable to send mail to ".$row['mail']);
    }
}

mysql_free_result($query);
mysql_close($connect); 
With mysql_fetch_array() we save data from the database to the variable $row, and send the mail.


Source Flat file (Click to View)

Source MySql (Click to View)

This code isn't a secure one, you should read how to secure your code.
http://www.supportforums.net/showthread.php?tid=700


Thank you for reading!
Reply
#2
Not bad but you should do some email validation checking. You also aren't checking for sql injection code.
Superman I am here to rescue you.
This is Support Forums not Support PMs.  Do not PM me for support unless it's private and site related.
Reply
#3
Thank you.

And yes that was on purpose, cause I'm planning a new tutorial about that.
Reply
#4
shouldn't you make a seperate file to store sql database info and block it with htaccess
Reply
#5
(10-08-2009, 03:29 PM)El Zorro Wrote: shouldn't you make a seperate file to store sql database info and block it with htaccess

Yes that would be better for you, this is just a simple code for learning not for real use.
Reply
#6
this is pretty cool thx
Reply
#7
Nice tut Ninjageek! Ima use the send email code to send registration validation for my website.
Reply
#8
Awsome Big Grin
Reply
#9
Thank you two.

(10-08-2009, 05:26 PM)MAcar Wrote: Nice tut Ninjageek! Ima use the send email code to send registration validation for my website.
That's nice.
Reply
#10
Nice share.
I was trying to get this by scraping sources from websites which had this. But now you made it easy for me.
Giveaway - A Rare Autoblog Guide. PM me for it, by clicking here.

Hey guys. It's Dr.Viper from HF. Howdy.
o HTML and PHP based website design.
o SEO/SEM services.
o Logo & GFX Design services.
And above all, everyone know what i'm good at HF... So,
o Security Consultancy.
Reply


Forum Jump:


Users browsing this thread: 3 Guest(s)