Managing a Simple Mailing List - Basic Projects - Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Part V. Basic Projects

Chapter 19. Managing a Simple Mailing List


In this chapter, you learn the following:

How to create a subscribe/unsubscribe form and script

How to create a front end for sending your message

How to create the script that sends your message


This chapter provides the first of several hands-on, small projects designed to pull together your PHP and MySQL knowledge. In this chapter, you learn how to create a managed distribution list that you can use to send out newsletters or anything else to a list of email addresses in a database.


Note

As with all the small sample projects in this book, these projects might not be exactly what you plan to build with your new PHP and MySQL knowledge. However, I cannot stress enough that the concepts and examples shown in this and other projects are similar to those you will encounter when developing any application that uses CRUD functionality (create, read, update, delete).


The mailing mechanism you use in this chapter is not meant to be a replacement for mailing list software, which is specifically designed for bulk messages. You should use the type of system you build in this chapter only for small lists, fewer than a few hundred email addresses.

Developing the Subscription Mechanism

You learned in earlier chapters that planning is the most important aspect of creating any product. In this case, think of the elements you need for your subscription mechanism:

• A table to hold email addresses

• A way for users to add or remove their email addresses

• A form and script for sending the message

The following sections describe each item individually.

Creating the subscribers Table

You really need only one field in the subscribers table: to hold the email address of the user. However, you should have an ID field just for consistency among your tables, and because referencing an ID is much simpler than referencing a long email address in where clauses. So, in this case, your MySQL query would look something like this:

CREATE TABLE subscribers (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
email VARCHAR (150) UNIQUE NOT NULL
);

Note the use of UNIQUE in the field definition for email. This means that although id is the primary key, duplicates should not be allowed in the email field either. The email field is a unique key, and id is the primary key.

Log in to MySQL via the command line and issue this query. After creating the table, issue a DESC or DESCRIBE query to verify that the table has been created to your specifications, such as the following:

mysql> DESC subscribers;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| email | varchar(150) | NO | UNI | NULL | |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

Now that you have a table in your database, you can create the form and script that place values in there.

Creating an Include File for Common Functions

Although there are only two scripts in this process, some common functions exist between them—namely, the database connection information. To make your scripts more concise in situations like this, take the common functions or code snippets and put them in a file to be included in your other scripts via the include() function that you learned about in Chapter 13, “Working with Files and Directories.” Listing 19.1 contains the code shared by the scripts in this chapter.

Listing 19.1 Common Functions in an Included File


1: <?php
2: // function to connect to database
3: function doDB() {
4: global $mysqli;
5:
6: //connect to server and select database
7: $mysqli = mysqli_connect("localhost", "joeuser",
8: "somepass", "testDB");
9:
10: //if connection fails, stop script execution
11: if (mysqli_connect_errno()) {
12: printf("Connect failed: %s\n", mysqli_connect_error());
13: exit();
14: }
15: }
16: // function to check email address
17: function emailChecker($email) {
18: global $mysqli, $safe_email, $check_res;
19:
20: //check that email is not already in list
21: $safe_email = mysqli_real_escape_string($mysqli, $email);
22: $check_sql = "SELECT id FROM SUBSCRIBERS
23: WHERE email = '".$safe_email."'";
24: $check_res = mysqli_query($mysqli, $check_sql)
25: or die(mysqli_error($mysqli));
26: }
27: ?>


Lines 3–15 set up the first function, doDB(), which is simply the database connection function. If the connection cannot be made, the script exits when this function is called; otherwise, it makes the value of $mysqli available to other parts of your script.

Lines 17–26 define a function called emailChecker(), which takes an input and returns an output—like most functions do. We look at this one in the context of the script, as we get to it in Listing 19.2

Save this file as ch19_include.php and place it on your web server. In Listing 19.2, you will see how to include this file when necessary in your scripts.

Creating the Subscription Form

The subscription form is actually an all-in-one form and script called manage.php, which handles both subscribe and unsubscribe requests. Listing 19.2 shows the code for manage.php, which uses a few user-defined functions to eliminate repetitious code and to start you thinking about creating functions on your own. The code looks long, but a line-by-line description follows (and a lot of the code just displays an HTML form, so no worries).

Listing 19.2 Subscribe and Unsubscribe with manage.php


1: <?php
2: include 'ch19_include.php';
3: //determine if they need to see the form or not
4: if (!$_POST) {
5: //they need to see the form, so create form block
6: $display_block = <<<END_OF_BLOCK
7: <form method="POST" action="$_SERVER[PHP_SELF]">
8:
9: <p><label for="email">Your E-Mail Address:</label><br/>
10: <input type="email" id="email" name="email"
11: size="40" maxlength="150" /></p>
12:
13: <fieldset>
14: <legend>Action:</legend><br/>
15: <input type="radio" id="action_sub" name="action"
16: value="sub" checked />
17: <label for="action_sub">subscribe</label><br/>
18: <input type="radio" id="action_unsub" name="action"
19: value="unsub" />
20: <label for="action_unsub">unsubscribe</label>
21: </fieldset>
22:
23: <button type="submit" name="submit" value="submit">Submit</button>
24: </form>
25: END_OF_BLOCK;
26: } else if (($_POST) && ($_POST['action'] == "sub")) {
27: //trying to subscribe; validate email address
28: if ($_POST['email'] == "") {
29: header("Location: manage.php");
30: exit;
31: } else {
32: //connect to database
33: doDB();
34:
35: //check that email is in list
36: emailChecker($_POST['email']);
37:
38: //get number of results and do action
39: if (mysqli_num_rows($check_res) < 1) {
40: //free result
41: mysqli_free_result($check_res);
42:
43: //add record
44: $add_sql = "INSERT INTO subscribers (email)
45: VALUES('".$safe_email."')";
46: $add_res = mysqli_query($mysqli, $add_sql)
47: or die(mysqli_error($mysqli));
48: $display_block = "<p>Thanks for signing up!</p>";
49:
50: //close connection to MySQL
51: mysqli_close($mysqli);
52: } else {
53: //print failure message
54: $display_block = "<p>You're already subscribed!</p>";
55: }
56: }
57: } else if (($_POST) && ($_POST['action'] == "unsub")) {
58: //trying to unsubscribe; validate email address
59: if ($_POST['email'] == "") {
60: header("Location: manage.php");
61: exit;
62: } else {
63: //connect to database
64: doDB();
65:
66: //check that email is in list
67: emailChecker($_POST['email']);
68:
69: //get number of results and do action
70: if (mysqli_num_rows($check_res) < 1) {
71: //free result
72: mysqli_free_result($check_res);
73:
74: //print failure message
75: $display_block = "<p>Couldn't find your address!</p>
76: <p>No action was taken.</p>";
77: } else {
78: //get value of ID from result
79: while ($row = mysqli_fetch_array($check_res)) {
80: $id = $row['id'];
81: }
82:
83: //unsubscribe the address
84: $del_sql = "DELETE FROM subscribers
85: WHERE id = ".$id;
86: $del_res = mysqli_query($mysqli, $del_sql)
87: or die(mysqli_error($mysqli));
88: $display_block = "<p>You're unsubscribed!</p>";
89: }
90: mysqli_close($mysqli);
91: }
92: }
93: ?>
94: <!DOCTYPE html>
95: <html>
96: <head>
97: <title>Subscribe/Unsubscribe to a Mailing List</title>
98: </head>
99: <body>
100: <h1>Subscribe/Unsubscribe to a Mailing List</h1>
101: <?php echo "$display_block"; ?>
102: </body>
103: </html>


Listing 19.2 might be long, but it’s not complicated. In fact, it could be longer were it not for the user-defined functions placed in ch19_include.php and included on line 2 of this script.

Line 4 starts the main logic of the script. Because this script performs several actions, you need to determine which action it is currently attempting. If the presence of $_POST is false, you know that the user has not submitted the form; therefore, you must show the form to the user.

Lines 6–25 create the subscribe/unsubscribe form by storing a string in the $display_block variable using the heredoc format. In the heredoc format, the string delimiter can be any string identifier following <<<, as long as the ending identifier is on its own line, as you can see in this example on line 25.


Note

You can learn more about the heredoc and other string formats in the PHP Manual at http://www.php.net/manual/en/language.types.string.php.


In the form, we use $_SERVER[PHP_SELF] as the action (line 7), and then create a text field called email for the user’s email address (lines 9–11) and set up a set of radio buttons (lines 13–21) to find the desired task. At the end of the string creation, the script breaks out of the if...elseconstruct, skips down to line 101, and proceeds to print the HTML stored in the $display_block variable. The form displays as shown in Figure 19.1.

image

Figure 19.1 The subscribe/unsubscribe form.

Back inside the if...else construct, if the presence of $_POST is true, you need to do something. There are two possibilities: the subscribing and unsubscribing actions for the email address provided in the form. You determine which action to take by looking at the value of $_POST['action']from the radio button group.

In line 26, if the presence of $_POST is true and the value of $_POST['action'] is "sub", you know the user is trying to subscribe. To subscribe, the user needs an email address, so check for one in lines 28–30. If no address is present, redirect the user back to the form.

However, if an address is present, call the doDB() function (stored in ch19_include.php) in line 34 to connect to the database so that you can issue queries. In line 36, you call the second of our user-defined functions: emailChecker(). This function takes an input ($_POST['email'], in this case) and processes it. If you look back to lines 21–25 of Listing 19.1, you’ll see code within the emailChecker() function that issues a query in an attempt to find an id value in the subscribers table for the record containing the email address passed to the function. The function then returns the resultset, called $check_res, for use within the larger script.


Note

Note the definition of global variables at the beginning of both user-defined functions in Listing 19.1. These variables need to be shared with the entire script, and so are declared global.


Jump down to line 39 of Listing 19.2 to see how the $check_res variable is used: The number of records referred to by the $check_res variable is counted to determine whether the email address already exists in the table. If the number of rows is less than 1, the address is not in the list, and it can be added. The record is added, the response is stored in lines 44–48, and the failure message (if the address is already in the table) is stored in line 54. At that point, the script breaks out of the if...else construct, skips down to line 101, and proceeds to print the HTML currently stored in$display_block. You’ll test this functionality later.

The last combination of inputs occurs if the presence of $_POST is true and the value of the $_POST['action'] variable is "unsub". In this case, the user is trying to unsubscribe. To unsubscribe, an existing email address is required, so check for one in lines 59–61. If no address is present, send the user back to the form.

If an address is present, call the doDB() function in line 64 to connect to the database. Then, in line 67, you call emailChecker(), which again returns the resultset, $check_res. Line 70 counts the number of records in the result set to determine whether the email address already exists in the table. If the number of rows is less than 1, the address is not in the list and it cannot be unsubscribed.

In this case, the response message is stored in lines 75–76. However, if the number of rows is not less than 1, the user is unsubscribed (the record deleted) and the response is stored in lines 84–88. At that point, the script breaks out of the if...else construct, skips down to line 101, and proceeds to print the HTML.

Figures 19.2 through 19.5 show the various results of the script, depending on the actions selected and the status of email addresses in the database.

image

Figure 19.2 Successful subscription.

image

Figure 19.3 Subscription failure.

image

Figure 19.4 Successful unsubscribe action.

image

Figure 19.5 Unsuccessful unsubscribe action.

Next, you create the form and script that sends along mail to each of your subscribers.

Developing the Mailing Mechanism

With the subscription mechanism in place, you can create a basic form interface for a script that takes the content of your form and sends it to every address in your subscribers table. This is another one of those all-in-one scripts, called sendmymail.php, and it is shown in Listing 19.3.


Note

Before attempting to use the script in this section, make sure that you have read the section in Chapter 11, “Working with Forms,” regarding the configuration in your php.ini file. The php.ini file is required to send mail.


Listing 19.3 Send Mail to Your List of Subscribers


1: <?php
2: include 'ch19_include.php';
3: if (!$_POST) {
4: //haven't seen the form, so display it
5: $display_block = <<<END_OF_BLOCK
6: <form method="POST" action="$_SERVER[PHP_SELF]">
7:
8: <p><label for="subject">Subject:</label><br/>
9: <input type="text" id="subject" name="subject" size="40" /></p>
10:
11: <p><label for="message">Mail Body:</label><br/>
12: <textarea id="message" name="message" cols="50" rows="10"></textarea></p>
13: <button type="submit" name="submit" value="submit">Submit</button>
14: </form>
15: END_OF_BLOCK;
16: } else if ($_POST) {
17: //want to send form, so check for required fields
18: if (($_POST['subject'] == "") || ($_POST['message'] == "")) {
19: header("Location: sendmymail.php");
20: exit;
21: }
22:
23: //connect to database
24: doDB();
25:
26: if (mysqli_connect_errno()) {
27: //if connection fails, stop script execution
28: printf("Connect failed: %s\n", mysqli_connect_error());
29: exit();
30: } else {
31: //otherwise, get emails from subscribers list
32: $sql = "SELECT email FROM subscribers";
33: $result = mysqli_query($mysqli, $sql)
34: or die(mysqli_error($mysqli));
35:
36: //create a From: mailheader
37: $mailheaders = "From: Your Mailing List
38: <you@yourdomain.com>";
39: //loop through results and send mail
40: while ($row = mysqli_fetch_array($result)) {
41: set_time_limit(0);
42: $email = $row['email'];
43: mail("$email", stripslashes($_POST['subject']),
44: stripslashes($_POST['message']), $mailheaders);
45: $display_block .= "newsletter sent to: ".$email."<br/>";
46: }
47: mysqli_free_result($result);
48: mysqli_close($mysqli);
49: }
50: }
51: ?>
52: <!DOCTYPE html>
53: <html>
54: <head>
55: <title>Sending a Newsletter</title>
56: </head>
57: <body>
58: <h1>Send a Newsletter</h1>
59: <?php echo $display_block; ?>
60: </body>
61: </html>


As in Listing 19.2, the file of user-defined functions is included on line 2. Although only the database connection function is used in this file, there’s no harm in having the other function in the file, as well.

The main logic of the script starts at line 3, where you determine whether the user has seen the form yet. If the presence of the $_POST variable is false, you know the user has not submitted the form; therefore, you must show the form.

Lines 5–15 create the form for sending the newsletter to your subscriber list, which uses $_SERVER[PHP_SELF] as the action (line 6), creates a text field called subject for the subject of the mail, and creates a textarea called message for the body of the mail to be sent.

At this point, the script breaks out of the if...else construct, and the HTML is printed. The form displays as shown in Figure 19.6.

image

Figure 19.6 Form for sending the bulk mail.

If the presence of $_POST is not false, the script should send the form to the email addresses in the subscribers table. Before sending the message, you must check for the two required items from the form in lines 18–20: $_POST['subject'] and $_POST['message']. If either of these items is not present, redirect the user to the form again.

If the required items are present, the script moves on to line 24, which calls the database connection function. A query is issued in line 33, which grabs all the email addresses from the subscribers table. There is no order to these results, although you could throw an order by clause in there if you want to send them out in alphabetic order for whatever reason.

Lines 37–38 create a From: mail header, which is used inside the upcoming while loop, when the mail is sent. This header ensures that the mail looks like it is from a person and not a machine because you’ve specifically provided a value in this string. The while loop, which begins on line 40, extracts the email addresses from the resultset one at a time. On line 41, you use the set_time_limit() function to set the time limit to 0, or “no limit.” Doing so allows the script to run for as long as it needs to.


Caution

Because the script in Listing 19.3 simply executes the mail() function numerous times, it does not take into account the queuing factors in actual mailing list software, which are designed to ease the burden on your outgoing mail server. Using set_time_limit() does not ease its burden; it just allows the script to continue to run when it might have timed out before.


In lines 43–44, the mail is sent using the mail() function, inserting the values from the form where appropriate. Line 45 adds to a string that is later printed to the screen, which shows to whom the mail was sent. Figures 19.7 and 19.8 show the outcome of the script.

image

Figure 19.7 Mail has been sent!

image

Figure 19.8 The mail arrived safely.

Summary

In this chapter, you applied your basic PHP and MySQL knowledge to the creation of a personal mailing list. Included were the database table creation, the subscribe and unsubscribe mechanisms, and the form and script for sending the mail.

Q&A

Q. How can I ease the burden on my mail server?

A. Besides looking into packaged mailing list software, you can bypass the mail() function and talk directly to your SMTP server via a socket connection. Such an example is shown in the PHP manual for the fsockopen() function (http://www.php.net/fsockopen), as well as in other developer resource sites.

Q. Where do bounced messages go?

A. As with any email (not just those sent in the manner described in this chapter), bounces go to whatever address you specify in your From: or Reply-to: mail headers.

Workshop

The workshop is designed to help you review what you’ve learned and begin putting your knowledge into practice.

Quiz

1. Which PHP function sends mail?

2. Why is $mysqli named as a global variable in Listing 19.1?

3. What PHP function call causes the script to execute for as long as it needs to run?

Answers

1. This is not a trick question. It’s the mail() function!

2. Because the variable $mysqli is created and assigned a value in a function that is included in one script for use by another, the variable must be declared as global to ensure it is usable outside of the confines of the function in which it was created.

3. set_time_limit(0)

Activities

1. Modify the manage.php script to display the user’s email as part of the response message for any action that is taken.

2. Modify the sendmymail.php script to add additional form fields that will correspond to section headings in the message string itself. Remember that when the form is submitted, those strings will have to be concatenated into one message string that is sent to the mail() function.