Gammadyne Corporation
Home Page Contact Us

Signup Forms

This article explains how to create a form on your website that allows a visitor to subscribe to a mailing list.  We will assume that you only need two pieces of information:  their name and email address.  The examples provided, which are written in PHP, can be easily modified to accept more fields.  Three types of mailing lists are demonstrated:  a plain-text file, a CSV file, and a database. 

The Form

First we will address the signup form.  You can either create a new page dedicated to just the form, or the form can be inserted into an existing page.

It is useful to perform some validation of the form fields.  Instead of blindly polluting your mailing list with invalid data, it is better to report the problem in a popup window.  Insert the following code inside your <head> element:

<script language="JavaScript" type="text/javascript">
<!--
// return true if 'e' is a valid simple email address
function validate_email(e) {
    if(e.indexOf('..') >= 0)
        return false;
    if(e.indexOf('<') >= 0)
        return false;
    if(e.indexOf('>') >= 0)
        return false;
    if(e.indexOf('"') >= 0)
        return false;
    if(e.charAt(0)=='.')
        return false;
    if(e.charAt(e.length - 1)=='.')
        return false;
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);
    }

// validate the form
function validate() {
    var s = document.ourform.name.value;
    if(s==null || s=="") {
        alert('Please enter your name.');
        document.ourform.name.focus();
        return false;
        }

    var s = document.ourform.email.value;
    if(s==null || s=="") {
        alert('Please enter your email address.');
        document.ourform.email.focus();
        return false;
        }
    if(!validate_email(s)) {
        alert('The email address is not valid.');
        document.ourform.email.focus();
        return false;
        }

    return true;
    }
//-->
</script>


Next, there is the form itself.  The following code implements a form that has two fields: the subscriber's name and email address.

<form action="signup.php" method=post name="ourform" onsubmit="return validate();">
Your name:<br>
<input size=70 maxlength=80 name=name id=name autofocus><br>
Your email address:<br>
<input size=70 maxlength=80 name=email id=email><br>
<br>
<center><input class=button type=submit value=" Subscribe "></center>
</form>


These fields are submitted to a PHP script named "signup.php".  The following three sections describe the contents of this script, depending on what type of mailing list you are using.

Plain Text Mailing List

If your mailing list is a simple, plain-text file with one email address per line, then the signup.php file looks like this:

<?php
$email = strtolower($_POST['email']);
$name = $_POST['name'];

// already subscribed?
$file = file_get_contents('c:\example\mailing list.txt');
$i = 0;
while(true) {
    $j = stripos($file, $email, $i);
    if($j===false)
        break;
        
    $ch = $file[$j - 1];
    if($ch=="\r" || $ch=="\n" || $ch=='<' || $j==0) {
        $ch = $file[$j + strlen($email)];
        if($ch=="\r" || $ch=="\n" || $ch=='>')
            die("You are already subscribed to this mailing list.");
        }
        
    $i = $j + strlen($email);
    }

// add new subscriber
$file = fopen('c:\example\mailing list.txt', 'a');
if(!$file)
    die("Error: failed to open mailing list.");

if($name=="")
    fwrite($file, $email . "\r\n");
else
    fwrite($file, "\"" . $name . "\" <" . $email . ">\r\n");

fclose($file);
echo "Your signup was successful.  Thanks!";
?>


Replace both instances of "c:\example\mailing list.txt" with the filepath of your mailing list.  Here is an example of how the file might look:

"Joe Schmoe" <joe@example.com>
nameless@example.com
"John Public" <john@example.com>

CSV Mailing List

If your mailing list is a CSV file, then the signup.php file looks like this:

<?php
$email = strtolower($_POST['email']);
$name = $_POST['name'];

// already subscribed? (assumes all cells are quoted)
$file = file_get_contents('c:\example\mailing list.csv');
if(stripos($file, '"' . $email . '"') != false)
    die("You are already subscribed to this mailing list.");

// open the file
$file = fopen('c:\example\mailing list.csv', 'a');
if(!$file)
    die("Error: failed to open mailing list.");

// if the file is new, write the column names on the first line
fseek($file, 0, SEEK_END);     // necessary due to a bug in fopen("a") and/or ftell()
if(ftell($file)==0)
    fwrite($file, "name,email\r\n");

// write the data record
fwrite($file, "\"" . $name . "\",\"" . $email . "\"\r\n");

fclose($file);
echo "Your signup was successful.  Thanks!";
?>


Replace both instances of "c:\example\mailing list.csv" with the filepath of your mailing list.  Here is an example of how the file might look:

name,email
"Joe Schmoe","joe@example.com"
"","nameless@example.com"
"John Public","john@example.com"

Database Mailing List

If your mailing list is in a database, you will need to install ODBC support into PHP.  For Microsoft IIS, this can be done in IIS Manager > Sites > [your website] > PHP Manager > PHP Extensions > Enable or disable an extension.  You must enable "php_pdo_odbc.dll".

The signup.php file looks like this:

<?php
$email = strtolower($_POST['email']);
$name = $_POST['name'];

// open the database
try {
    $db = new PDO("odbc:my_dsn", "my_user", "my_password");
}
catch(PDOException $e) {
    echo "Failed to open database.\r\n" . $e->getMessage();
    return;
    }

// already subscribed?
$sql = "SELECT my_email_column FROM my_table WHERE my_email_column LIKE '$email'";
foreach($db->query($sql) as $row) {
    if($email==strtolower($row['my_email_column']))
        die("You are already subscribed to this mailing list.");
    }

// add new subscriber
$sql = "INSERT INTO my_table (my_email_column, my_name_column) VALUES ('$email', '$name')";
if(!$db->query($sql)) {
    echo "<pre>Failed to add subscriber.\r\n";
    print_r($db->errorInfo());
    echo "</pre>";
    return;
    }

echo "Your signup was successful! Thanks!";
unset($db);
?>


Make the following replacements in the above script:

Replace ThisWith This
my_dsnThe name of the ODBC Data Source.  This must be created in the ODBC Administrator under the "System DSN" tab.
my_userThe user name required for database authentication.
my_passwordThe password required for database authentication.
my_tableThe name of the table that holds the mailing list.
my_email_columnThe name of the column that holds the subscriber's email address.
my_name_columnThe name of the column that holds the subscriber's name.

See Also

The sister article, Optout Forms, explains how to create a form that unsubscribes a recipient.

Javascript
PHP
PHP Data Objects (PDO)
ODBC
ODBC Administrator

If you find a mistake, please let us know.