Make your own free website on

Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

The Code Explained: Subscription

Just a few lines of code do the actual subscription:

Our code first of all tries to open the datafile for append:

if(!$dfHandle = fopen($datafile,'a+')){
  print "Internal Error.  Cannot open data file";

This code could be made shorter if we used die() instead of exit() - in which case the code could have read:

$dfHandle = fopen($datafile, 'a+') 
       or die("Internal error.  Cannot open data file";

However, if the file opens successfully, we read the entire file into array using the file() function and rewind the array pointer so that it point to the beginning of the array:

$allFile = file($datafile);
reset($allFile); //rewind array pointer

We need to ensure that one email address does not appear more than once in our database so we will search through the entire array to ensure that it doesn't exist. The only disadvantage with this approach is that the datafile may be so big and reading it all into the RAM may actually be very tasking to the computer resources. This is why we unset it immediately after:

while(list($linenum,$line) = each($allFile)){
   $items = preg_split("/\|/",$line);
   if(preg_match("/^$mail$/", $items[2]) ){
	print "

Cannot add $items[2]. It already exists in the mailing list."; exit(); } } unset($allFile); //release variable - save RAM

If the email address does not exist, we create a string containing the first name, last name, email address and A NEW LINE character and then add it to the database and thank the user personally:

$writeString = "$fName|$lName|$mail\n";
print "

Thank you $lName. Your address $mail has been added". " to the PHP mailing list";

That is the entire subscription script! So easy wouldn't you say? Now let's look into unsubscription.

<< Diving the Code | Code Explanation: Un-Subsrcibe >>

JamHitz Productions