Last Updated:

Develop your own mailing lists using PHP

There are many ways to use mechanisms such as mailing lists, from notifying users about updates to your site to informing interested people about changes you have made while working on a particular project. However, maintaining a complex mechanism such as a mailing list manually, without the appropriate software solutions, can be a rather time-consuming process. At the same time, the development of scripts that allow you to easily administer a mailing list of any complexity, and visitors without your participation to subscribe or unsubscribe from certain news, is not an insoluble task even for a person inexperienced in Internet programming.

The simplest solution to this problem, in my opinion, is the development of appropriate scripts in the PHP language, since support for this language is included in the set of services of almost any company that provides hosting services. With PHP, you will be able to develop full-featured applications that can be accessed from anywhere in the world via the Internet. Of course, there are many applications that can provide you with all the necessary functions to manage mailing lists, but all of them (except for the need to pay for their purchase) have the following drawback: you will not be able to 100% customize the application as you would like. You will always be dissatisfied with something. And the development of your own PHP scripts will provide you with a guarantee that at any time you can modify the existing mechanism of the mailing list.

For the purposes of this article, I propose to consider the solution to the problem of organizing a mailing list. For simplicity, no DBMS will be used here, and flat files will take its place. This is done only for the purpose of simplification, since talking about using, in particular, MySQL, can take a long time, and not everyone will need to work with large mailing lists. For some, a list of 300-500 addresses will be enough, with which the flat file technology copes perfectly and without slowing down. While buying hosting with MySQL support costs more than hosting with PHP, but without the ability to work with databases.

Later in this article, I will try to outline to you the basic principles of creating and manipulating mailing lists using the mechanisms provided by PHP. For those who are not familiar enough with this powerful programming language for Web-server applications, a few words about what PHP is. It is an interpreted language for creating active Web pages. A PHP program, like text in JavaScript, VBScript or ASP, is inserted into an HTML file (or into a separate file with the appropriate extension). The beginning and end of the program are marked with special brackets. PHP does not interpret text outside of these parentheses: it is passed to the Web browser "as is". The syntax of PHP is based on the syntax of C, Java, and perl and is described in some detail in the included manual (it can also be taken from the http://www.php.net node).

We send letters

So, let's determine that all scripts will be located in the root directory, and data files - in the data/ directory. Each of the mailing lists will be stored in a separate file. In addition, a log file will be organized, also in the form of a simple test file. The list of mailing lists will be stored in the lists file.txt in the data directory, each line of which will contain the name of the list and the name of the file in which the e-mail addresses of subscribers are stored. The fields will be separated by a "|" symbol. This file will be used to form a drop-down list in the form of administration to manipulate a particular address list. I am in favor of providing access to the most commonly used mechanisms in the simplest way. That is why I propose to place on the start page a form for sending messages to the members of the mailing list, and to provide access to other administrative mechanisms to organize using links. So, I suggest you take a look at the text of the index.php file below. Figure 1 shows the result of accessing it through the browser.

<html><head><title>Mailing List Administration</title></head>
<body>
<center><H2> Administration of mailing lists </H2></center>
<form method=post action="sendemail.php">
<table>
<tr align="left">
<td width="200" align="left">
<b>Sender's address:</b>
</td>
<td align="left" width="50">
<input type=text name="From" size="40" value="">
</td>
</tr>
<tr>
<td align="left">
<b>Subject:</b>
</td>
<td align="left">
<input type=text name="Subject" size="40">
</td>
</tr>
<tr>
<td align="left">
<b>Select list:</b>
</td>
<td align="left">
<select name="List" size=1>
<?
$groups = file("data/lists.txt");
for ($index=0; $index < count($groups); $index++)
{
$grouplist = split("\|", chop($groups[$index]));
?>
<option value="<? print $grouplist[1] ?>"
<? if ($index==0)
{print "selected";}
?>
>
<?
print $grouplist[0]
?>
</select>
</td>
</tr>
<td align="left">
<b>Message text:</b>
</td>
<td align="left">
<textarea cols=50 rows=10 name="Body"></textarea>
</td>
</tr>
</table>
<input type="submit" name="Submit" value="Submit">
</form>
<a href="newlist.php">Creating a new mailing list sheet.</a>
<br><a href="addnames.php">Add addresses to list</a>.
<br><a href="picklist.php">Modifying/deleting addresses</a>.
<br><a href="data/log.txt">View Log</a>.
<br><a href="autoresponder.php"> View/edit autoresponder</a>.
</body></html>

Most likely, you have noticed that the above text is mostly plain HTML code. The exception is strings bounded by parentheses. The text between them is the commands of the PHP language. Let's take a closer look at what kind of task they perform. In principle, everything is quite simple. The $groups variable contains the contents of the lists.txt file located in the data/ directory. Then, in a loop, each row is divided into fields, for which the expression is used

$grouplist = split("\|", chop($groups[$index])); 

From the received list names and corresponding files, a set of option tags of the select input element is formed (the result is visible in Figure 1). Use the chop function to remove duplicate spaces and a newline character.

To simplify the work, you can directly in the file to write the text in the input element of the sender's address, which is used by default. This will save you from having to enter the same address every time.

So, after clicking on the "Send" button, the control along with all the entered data is transferred to a script named sendemail.php. The code that sends messages is quite simple and is presented below:

<html><head><title>Sending mail...</title></head><body>
<?
$addresses = file("data/$List");
for ($index=0; $index < count($addresses); $index++)
{
mail("$addresses[$index]","$Subject",
"$Body","From: $From\nReply-To: $From");
}
$myfile = fopen("data/log.txt","a");
fputs($myfile, $Subject."\t".date("dS of F Y h:i:s A")."\t".$List."\n");
fclose($myfile);
?>
Your message has been sent.
<br><br>
<a href="index.php">Home</a>.
</body></html>

This script uses several very useful functions. The first is mail(), one of the most powerful and at the same time easy-to-use functions included in PHP. When running a Web server running a UNIX operating system, the mail() function uses sendmail by default, but the PHP setting can be changed and any other mechanism specified in the corresponding section of the php.ini file can be used to send mail. The mail() function is described as follows:

mail (string to, string subject, string message, string [additional_headers]); 

As a value for the additional_headers parameter, you can specify the information that you want, including parameters such as X-Mailer, Reply-To, CC:, Bcc, Mime-Version, or you can also form your own title.

To get a list of e-mail addresses from the corresponding file, use the file() function. The file name is passed as a parameter when the form's data processing script is called. Then the message is sent in a loop to all addresses.

Add addresses to the mailing list

The next issue I would like to address in this article is the mechanism for adding new addresses to a particular mailing list. To provide such a possibility, we need to create a PHP file with an address input form, as well as a script that processes this information. First, here is the text of the addnames.php file, the result of which is shown in Figure 2.

<html><head><title>Adding an address to a mailing list</title></head>
<body>
<center><H2>Adding an address to a mailing list</H2></center>
<form method=post action="sevemail.php">
<table>
<tr>
<td align="left">
<b>Select list:</b>
</td>
<td align="left">
<select name="List" size=1>
<?
$groups = file("data/lists.txt");
for ($index=0; $index < count($groups); $index++)
{
$grouplist = split("\|", chop($groups[$index]));
?>
<option value="<? print $grouplist[1] ?>"
<? if ($index==0)
{print "selected";}
?>
>
<?
print $grouplist[0]
?>
</option>
<?
}
?>
</select>
</td>
</tr>
<tr>
<td align="left">
<b>Email to add:</b>
</td>
<td align="left">
<input type=text name="Email" size="40">
</td
</tr>
</table>
<input type="submit" name="Submit" value="Add address">
</form>
<a href="newlist.php">Creating a new mailing list sheet.</a>
<br><a href="picklist.php">Modifying/deleting addresses</a>.
<br><a href="data/log.txt">View Log</a>.
<br><a href="autoresponder.php"> View/edit autoresponder</a>.
</body></html>

The only difference between this file and index.php is the absence of input fields that are specific only to sending letters, as well as the name of the script to which control is transferred after clicking on the "Add address" button. The following is the text of the savemail.php script.

<html><head><title>Writing a file...</title></head><body>
<br><br>
<?
if (file_exists("data/$List"))
{
$myfile = file("data/$list");
$fh = fopen("data/$List","w");
for ($index=0; $index < count($myfile); $index++)
{
if ($Email != chop($myfile[$index]))
{fputs($fh,$myfile[$index]);}
}
fputs($fh,$Email."\n");
fclose($myfile);
}
else
{
$myfile = fopen("data/$List","w");
fputs($myfile,$Email."\n");
fclose($myfile);
}
?>
<br>
<? echo $Email ?> written to <? echo $List ?>
<br><br>
<a href="index.php">Home</a>.
</body></html>

Let's consider the tasks that this script must perform. First, checking for the existence of the address list file. This is done using the file_exists function. If a file with the specified name does not exist, it means that the address we add is the first in the list. In this case, just create a new file and write an e-mail address to it. Otherwise, after reading the already generated list, you should add the e-mail address transmitted from the form to the array, but first you should see if it is entered earlier, because none of the addresses should be duplicated. This, in particular, can be done in a loop across all elements of the array. In this case, the list file will be opened for reading, and all addresses that do not coincide with the newly written address will be written to it. Note that the fopen file open function uses "w" as the second parameter. This means that the file is opened to write data to it. The value "r" would mean opening the file for reading, "a" - to add information to existing data. The format for calling the fopen function is as follows:

fopen (filename, mode) 

Pay attention to the following nuance: if you are going to open a file simultaneously for reading and writing, you should provide for the possibility of incorrect shutdown of the script. After opening the file, you should read all its contents into an array and make all modifications with the data in memory. Only after processing all the data can you reopen the file, now for writing, and put the modified information in it.

The mechanism for adding e-mail addresses that we have considered is largely imperfect. For example, instead of one address, you can provide for the input of several at once. To do this, you just need to change the description of the form in the addnames.php file, as well as slightly correct the code for processing the data passed to savemail.php. In addition, you can check the correctness of the e-mail address input using a certain pattern (for example, the presence of the "@" symbol inside the string). I won't go into too much detail, as it can take a long time, especially since my goal at the moment is to demonstrate the capabilities of the PHP language, and also that the task of creating such a powerful mechanism as a mailing list management system is not so difficult. However, I suggest moving on to the next step - creating new mailing lists. As in the previous case, to do this, you need to create two files, the first of which will contain a form for entering the initial data, and the second will process this data. Let's call these files newlist.php and makenewlist.php respectively.

newlist.php:
<html><head>
<title>Sozdaniye novogo spiska rassylki</title>
</head>
<body>
 <center>
<H2>Sozdaniye novogo spiska</H2></center> <form method=post action="make-newlist.php"> <table> <tr> <td align="left"> <b>Nazvaniye spiska:< /b> </td> <td align="left"> <input type=text name="Listname" size="40"> </td> </tr> <tr> <td align="left"> <b>Description(odno slovo):</b> </td> <td align="left"> <input type=text name="Filename" size="40"> </td> </tr> < /table> <input type="submit" name="Submit" value="Zapisat'"> </form> <br><a href="addnames.php">Dobavit' adresa v spisok</a>. <br><a href="picklist.php">Modifikatsiya/udaleniye adresov</a>. <br><a href="data/log.txt">View zhurnala</a>. <br><a href="autoresponder.php"> Prosmotr/redaktirovaniye avtootvetchika</a>. </body></html> makenewlist.php: <html><head><title>Sozdaniye fayla...</title></head><body> <? $Filename = $Filename.".lst"; $myfile = fopen("data/lists.txt","a"); fputs($myfile,$Listname."|".$Filename."\n"); fclose($myfile); ?> Sozdan spisok rassylki <? echo $Listname ?>.<br> <br> <a href="index.php">Na glavnuyu</a>. </body></html>
Show more
1.093 / 5.000
translation results
newlist.php:
<html><head><title>Creating a New Mailing List</title></head>
<body>
<center><H2>Creating a new list</H2></center>
<form method=post action="make-newlist.php">
<table>
<tr>
<td align="left">
<b>List name:</b>
</td>
<td align="left">
<input type=text name="Listname" size="40">
</td>
</tr>
<tr>
<td align="left">
<b>Description(one word):</b>
</td>
<td align="left">
<input type=text name="Filename" size="40">
</td>
</tr>
</table>
<input type="submit" name="Submit" value="Submit">
</form>
<br><a href="addnames.php">Add addresses to list</a>.
<br><a href="picklist.php">Modifying/deleting addresses</a>.
<br><a href="data/log.txt">View Log</a>.
<br><a href="autoresponder.php"> View/edit autoresponder</a>.
</body></html>
makenewlist.php:
<html><head><title>Creating File...</title></head><body>
<?
$Filename = $Filename.".lst";
$myfile = fopen("data/lists.txt","a");
fputs($myfile,$Listname."|".$Filename."\n");
fclose($myfile);
?>
Created mailing list <? echo $listname ?>.<br>
<br>
<a href="index.php">Home</a>.
</body></html>

It is easy to see that the makenew-list.php script performs only one function - adding the name of the list and the name of the corresponding file to lists.txt.

Edit addresses

To edit the e-mail addresses of the mailing list as a simple and, nevertheless, effective solution, you can use direct editing of the text of the corresponding file. First of all, we should have a form in which we will select an editable mailing list. The text of the corresponding file is as follows: As you can see, it is not very different from previous forms files and is given here solely to demonstrate the simplicity of developing this type of form (for those readers who are not yet a professional in php programming).

<html><head><title>Editing addresses</title></head>
<body>
<center><H2>Editing addresses</H2></center>
<form method=post action="editnames.php">
<table>
<td align="left">
<b>Select list:</b>
</td>
<td align="left">
<select name="List" size=1>
<?
$groups = file("data/lists.txt");
for ($index=0; $index < count($groups); $index++)
{
$grouplist = split("\|", chop($groups[$index]));
?>
<option value="<? print $grouplist[1] ?>"
<? if ($index==0)
{print "selected";}
?>
>
<?
print $grouplist[0]
?>
</option>
<?
}
?>
</select>
</td>
</tr>
</table>
<input type="submit" name="Submit" value="Edit">
</form>
<a href="newlist.php">Creating a new mailing list sheet.</a>
<br><a href="addnames.php">Add addresses to list</a>.
<br><a href="data/log.txt">View Log</a>.
<br><a href="autoresponder.php"> View/edit autoresponder</a>.
</body></html>

Now that you have created the first form, you should write a script that displays the contents of the mailing list. To do this, we read the contents of the file corresponding to the selected worksheet and then place its contents in an input element of type textarea:

<html><head><title>Editing addresses</title></head><body>
<form method=post action="writenamefile.php">
<br>
Editing <? echo $List ?>.
<br><br>

Edit the existing addresses or exclude them from the list by deleting the entire row.

<b>Blank lines are not allowed!</b>
<br><br><textarea cols=50 rows=20 name="Body">
<?
if (file_exists("data/$List"))
{readfile("data/$List");}
?>
</textarea>
<br><br>
<input type="hidden" name="List" value="<? echo $List ?>">
<input type="submit" name="submit" value="Save"></FORM>
<br>
<a href="index.php">Home</a>.
</body></html>

Notice how we pass the name of the address list file to the script.php the name of the address list file:

<input type="hidden" name="List" value="<? echo $List ?>"> 

I also want to mention the function we used to pass the contents of a file directly to the form: readfile(). There are no checks in this file (in particular, for the correctness of addresses). When developing your own scripts, you could implement this kind of mechanism using, for example, JavaScript. The output of the editnames.php script is shown in Figure 3.

The next step is to develop a script responsible for writing the edited data to the file. Here everything is very simple: we get the data from the input element of the textarea type (variable $Body) and write its contents to the file:

<html><head><title>Saving changes...</title></head><body>
<br><br>
The changes are saved in the list <? echo $List ?>.<br>
<?
$myfile = fopen("data/$List","w");
fputs($myfile,$Body);
fclose($myfile);
?>
<br>
<a href="index.php">Home</a>
</body></html>

Answering machine

As part of our conversation today, autoresponders will be understood as a mechanism that sends an e-mail message to the user after the completion of some action. For example, this event can be a visitor's subscription to the newsletter. To edit the text of the message sent by the autoreport script, the same technology can be used as when editing the address list. First, create a form to edit the message:

autoresponder.php:
<html><head><title>Setting up an autoresponder</title></head><body>
<form method=post action="writeautoresponder.php">
<br>

The following is an automated message that is sent to users who have subscribed to the admin newsletter.

<br><br>
<textarea cols=70 rows=20 name="Body">
<? readfile("data/autoresponder.txt"); ?>
</textarea>
<br><br>
<input type="submit" name="submit" value="Save changes"></FORM>
<br>
</body></html>

Secondly, we write a script that saves the changes made by the administrator in the corresponding file (autoresponder.txt.

writeautoresponder.php

<html><head><title>Saving changes...</title></head><body>
<br><br>
<b>The following message has been saved and is used by the autoresponder:</b><br>
<?
$myfile = fopen("data/autoresponder.txt","w");
fputs($myfile,$Body);
fclose($myfile);
?>
<br>
<pre><? echo $Body ?> </pre><br>
<br>
<a href="index.php">Home</a>

Now you should ensure that visitors can subscribe to the mailing list. To do this, let's create an HTML file with something similar to the following:

<b>Receive server news for administrators by e-mail:</b><br>
<form method="post" action="thanks.php">
<input type="text" name="Email" size="20">
<input type="hidden" name="List" value="admins.txt">
<input type="submit" Value="Subscribe"></form>

The result of accessing this file from the browser window is shown in Fig. 4. The last one for today will be the script for placing a new e-mail address in the corresponding mailing list. In our case, the worksheet file is named "admins.txt" (note the hidden List parameter). The thanks.php script code is shown below:

<html><head><title>Thank you!</title></head><body>
<?
$Body = readfile("data/autoresponder.txt");
mail("$Email","Newsletter Subscription","$Body","From: Me\nReply-To: me@myaddress.com");
$myfile = file("data/admins.lst");
$fh = fopen("data/admins.lst","w");
for ($index=0; $index < count($myfile); $index++)
{
if ($Email != chop($myfile[$index]))
{fputs($fh,$myfile[$index]);}
}
fputs($fh,$Email."\n");
fclose($fh);
?>
Thank you for subscribing to our newsletter!
<br><br>
</body></html>

That's it. Now, I hope you have the opportunity to develop your own mailing lists.

Conclusion

The option of organizing mailing lists discussed above is not ideal. There's always a need to tweak something. In particular, when entering information, it would be possible to organize data validation using JavaScripts. In addition, using MySQL databases rather than flat files as data stores can make these scripts more productive, especially if you intend to create mailings for a large number of clients. Moreover, this is done simply - instead of writing/reading commands to the file, SQL queries to the database are used.

I hope that I was able to demonstrate to you the power and simplicity of the PHP language, especially since even the above scripts, with a small upgrade, can be used for completely different tasks.