Imagine you have to create a mailing list for your site visitors. When we plan this process these are the normal steps which we need to concentrate on:1. Creating a HTML form to input email addresses of visitors. (input.htm)2. PHP page to receive the email address from the HTML page and write them in a text file. (submit.php)3. Read the text file and send an email to all subscribers. (send.php)
We'll start off the project by stepping on to the first one. Create a simple HTML form with one text field and a submit button.
This will post the email address to the submit.php. What are we waiting for? We can also code it now as you have already learnt all the functions you'll be experiencing on this page.
submit.php
<?php $emailAddress = $_POST['emailadd'];
if(!$emailAddress) // If email address is not entered show error message { echo "Please enter your email address."; exit; } else { $filename = "subscribers.txt"; // File which holds all data $content = "$emailAddress\n"; // Content to write in the data file $fp = fopen($filename, "a"); // Open the data file, file points at the end of file $fw = fwrite( $fp, $content ); // Write the content on the file fclose( $fp ); // Close the file after writing
if(!$fw) echo "Couldn't write the entry."; else echo "Successfully wrote to the file."; } ?>
That's it. I hope you could understand the process with the help of comments written inside the code. This code simply checks whether user has entered an email address. Then if he hasn't entered, it shows an error message, or if he has entered an address, it writes it into the text file where all the addresses are stored.
The next part of the project is retrieving all email addresses in the file and sending emails to all of them. Let's go through that part and sum up the project now.
send.php
<?php $filename = "subscribers.txt"; // File which holds all data $arrFp = file( $filename ); // Make array of file content lines $numAdds = count( $arrFp ); // Count no. of elements in the array, count email addresses
for($i=0; $i<$numAdds; $i++) { $emailAddress = trim( $arrFp[$i] ); // Trim email addresses before sending mails echo "Sending email to $emailAddress..."; $success = mail( $emailAddress, "Test email", "This is a test email message");
As I told you in a prior chapter, here we have an example of the file() function. In the second line of this code, there is a new array getting created called, $arrFp which holds an email address as each element. Then you can basically loop through the array and send mails to everyone.