Form to Email/SQL Part 3

Here I'll create the functions that are called from the formtop script. For convenience I've divided the functions into two sections. The first section adresses security and validation of your data. The second storage and transmission of the data.

To stop malicious scripts the referring url is tested to see if the script comes from your own website and clears possible sql injection. Compulsory fields are checked to see that they do indeed contain data and the format of email address is checked to see if it is valid

// stop cross domain scripting
function checkDomain(){
$referer=strtolower(substr($_SERVER['HTTP_REFERER'],7));//clear http://
if (substr($referer,0,4)=="www.") $referer=substr($referer,4); //clear www.
if (substr($hostdomain,0,4)=="www.") $hostdomain=substr($hostdomain,4); //clear www.
if (substr($referer,0,strlen($hostdomain)) != $hostdomain ){
header ("location: ".$_SERVER['HTTP_REFERER']);// send them back
exit("not allowed");// To be safe Stop the script.
// check that all compulsary fields have a value.
//return with an error if one or more are missing.
function checkCompulsary($_POST,$compulsory){
foreach ($compulsory as $key=>$value){
if ($_POST[$value]==""){
$error="Please Complete all fields marked with an *";
return $error;
//Check for attempted SQL injection 
function checkSQl($_POST){
foreach ($_POST as $key=>$value)
return $_POST;
// Function to  check fo a valid email format.
function checkEmail($email) {
  // First, we check that there's one @ symbol, and that the lengths are right
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
    return false;
  // Split it into sections to make life easier
  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
     if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
      return false;
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
        return false;
  return $email;

Once the data has been checked it must be stored and/or email out. If you have set fullemail to 1 in the configuration all the form data will be sent to the user with a copy to the $fromemail address otherwise just a simple acknowledgement is sent to the user but the full details sent to the $fromemail address.If you are using a database the data will be stored in the MySQL table. If you have set usePassword and / or optin URL those details will be also be included in the database and sent to the user.

function sendEmail($_POST,$password,$optinstring,$fullEmail,$fromEmail){


Create a new database and a user name and password. With one table with a unique id field plus the fields that the user input on their form.

Double optin

This is a method to allow your users a chance to confirm their email address. When a user completes the form they are sent and email with an encrypted key included in a link back to your site. They must click the link to confirm it is indeed them who has sent the email and the wish to procede. This safeguards the webmaster from sending out spam inadvertantly. I have included this facility in this system.

You therefore need two extra fields in your database table: optin_key and optin_flag, plus one further field - password in case you want to use the database for a login in script.

Open PHP my admin go to the database you have created click on SQL then copy and paste the following code and click on "Go".

CREATE TABLE `emailform` (
  `id` int(6) NOT NULL auto_increment,
  `name` varchar(40) NOT NULL,
  `surname` varchar(40) default NULL,
  `email` varchar(60) NOT NULL,
  `comment` text,
  `optin_key` varchar(20) NOT NULL,
  `optin_flag` binary(1) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  UNIQUE KEY `name` (`name`)

Now to create a configuration file. If you are using a database change your databse login details and the database name. List the compulsory fields and if you do not want to use double opt in change the $optin to 0. For format of the emails see the later in the article. If $usePassword=1 then a password is generated and sent to the user.

// Mysql details
$shortemail=1;//send just an acknowledgement to user;
$longemail=1;//send full form details to user;
$usePassword=1;//create a password;

The PHP code

The code uses session variables. It is important that the code to start the session is the first thing sent out by the page so ensure there are no spaces before the opening <?php. The first check is to see if the submit button has been pressed. The code then loops through the information from the form (stored in the $_POST array) to ensure that there has not been an attempt at SQL injection. Then verify that the email conforms to the correct pattern and the compulsory fields are all completed.

if ($_POST['Submit']){
extract ($_POST);
If (!$email) {
$error.="Please Supply A Valid Email Address<br />";
If (strtolower($captcha)!=$_SESSION['captcha'])
$error.="You entered an incorrect capture code<br />";
if ($error)return;
if ($usePassword)
for ($i=0;$i=7;$i++){
if ($optin){
for ($i=0;$i=7;$i++){
if ($dbuser)addtodb($_POST,$password,$optinstring);
if ($shortemail)shortEmail($_POST,$password,$optinstring,$fromEmail);
if ($longemail)longEmail($_POST,$password,$optinstring,$fromEmail);

Now create the functions.

Previous Next