PHP form validation and post sending

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dboco
Forum Newbie
Posts: 5
Joined: Thu Feb 11, 2010 4:19 pm
Location: Slovenia

PHP form validation and post sending

Post by dboco »

hi, I am very new to php and I need a little help from you.
On my side I want contact form, so I grab some validation and emaling codes and put them together with html.
Code post data from form to my email, but it not validating inputs realtime after pushing submit button. I do not know what I have done wrong please help me to find out ...
BTW, I want to add check box for desiding user, if he want to confirm a copy of form on his mail. How do I do that?

Here is code so far:

Code: Select all

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
  <style>
    .errText {
        font-family: Arial;
        font-size: 10px;
        color: #CC0000;
        text-decoration: none;
        font-weight: normal;
    }
 
    body {
       font-family: Arial;
       font-size: 14px;
       color: #ffffff;
       font-weight: normal;
    }
 
  </style>
 
  <title>CONTACT</title>
  
  <?php
      $errFirstName = "";
      $errLastName = "";
      $errCompanyName = "";
      $errAddress = "";
      $errPostalCode = "";
      $errPhone = "";
      $errFax = "";
      $errEmail = "";
      $errSubject = "";
      $errComment = "";
 
        
      if($_POST["contact1"]=="info"){
 
        if(preg_match("/^[A-Z][a-zA-Z -']+$/", $_POST["firstname"]) === 0)
          {$errFirstName = '<p class="errText">First Name must be from letters, dashes, spaces and must not start with dash</p>';
             $error=true;
        }
 
        if(preg_match("/^[A-Z][a-zA-Z -']+$/", $_POST["lastname"]) === 0)
          {$errLastName = '<p class="errText">Last Name must be from letters, dashes, spaces and must not start with dash</p>';
             $error=true;
        }
 
        if(preg_match("/^[A-Z][a-zA-Z -']+$/", $_POST["companyname"]) === 0)
          {$errCompanyName = '<p class="errText">Company Name must be from letters, dashes, spaces and must not start with dash</p>';
             $error=true;
        }
 
 
        if(preg_match("/^[a-zA-Z0-9 _.,:\"\']+$/", $_POST["address"]) === 0)
          {$errAddress = '<p class="errText">Address must be only letters, numbers or one of the following ". , : /"</p>';
             $error=true;
        }
 
        if(preg_match("/^\d{4}$/", $_POST["postalcode"]) === 0)
          {$errPostalCode = '<p class="errText">Postal Code must be 4 digits</p>';
             $error=true;
        }
 
        if(preg_match("/^\d{1}-\d{3}-\d{3}-\d{4}$/", $_POST["phone"]) === 0)
          {$errPhone = '<p class="errText">Phone must comply with this mask: 1-333-333-4444</p>';
             $error=true;
        }
 
        if(preg_match("/^\d{1}-\d{3}-\d{3}-\d{4}$/", $_POST["fax"]) === 0)
          {$errFax = '<p class="errText">Fax must comply with this mask: 1-333-333-4444</p>';
             $error=true;
        }
 
        if(preg_match("/^[a-zA-Z]\w+(\.\w+)*\@\w+(\.[0-9a-zA-Z]+)*\.[a-zA-Z]{2,4}$/", $_POST["email"]) === 0)
          {$errEmail = '<p class="errText">Email must comply with this mask: chars(.chars)@chars(.chars).chars(2-4)</p>';
             $error=true;
        }
 
        if(preg_match("/^[A-Z][a-zA-Z -']+$/", $_POST["subject"]) === 0)
          {$errSubject = '<p class="errText">Subject must be from letters, dashes, spaces and must not start with dash</p>';
             $error=true;
        }
 
        if(preg_match("/^[A-Z][a-zA-Z -']+$/", $_POST["comment"]) === 0)
          {$errComment = '<p class="errText">Comment must be from letters, dashes, spaces and must not start with dash</p>';
             $error=true;
        }
 
          
  ?>
 
 
<?php
if ($_POST["contact1"]<>'' && $error==false) {
   $ToEmail = 'my.3home.email@gmail.com';
   $EmailSubject = 'Contact form';
   $mailheader = "From: ".$_POST["email"]."\r\n";
   $mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
   $mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
   $mailheader .= "Content-type: text/plain; charset=iso-8859-1\r\n";
   $MESSAGE_BODY .= "FirstName: ".$_POST["firstname"]."<br>";
   $MESSAGE_BODY .= "LastName: ".$_POST["lastname"]."<br>";
   $MESSAGE_BODY .= "CompanyName: ".$_POST["companyname"]."<br>";
   $MESSAGE_BODY .= "Address: ".$_POST["address"]."<br>";
   $MESSAGE_BODY .= "PostalCode: ".$_POST["postalcode"]."<br>";
   $MESSAGE_BODY .= "Phone: ".$_POST["phone"]."<br>";
   $MESSAGE_BODY .= "Fax: ".$_POST["fax"]."<br>";
   $MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>";
   $MESSAGE_BODY .= "Subject: ".nl2br($_POST["subject"])."<br>";
   $MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"])."<br>";
   mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("ERROR!!!");
}
?>
 
 
 
<center>
   <h1 style="color:#ffa500">
      <br>
      <br>
      THANK YOU! Your message is send!
      <br>
      our team
      <br>
      <br>
   </h1>
   <br>
   <br>
   <br>
   <h2 style="color:#0088cc">
      Click <a href="http://www.testarea.slowebdesigner.eu/testk2/contact1.php" target="_parent">here</a> for back.
</center>
 
 
<?php
}else {
?>
 
 
 
 
</head>
 
  <body>
  <center>
  <form enctype="multipart/form-data" name="contact1" action="<?php $PHP_SELF ?>" method="POST">
    <input type="hidden" name="contact1" value="info">
    <table width="500" border="0" cellpadding="4" cellspacing="0" bordercolor="#000000" bgcolor="#ffa500">
      <tr align="center">
        <td colspan="2"><strong style="font-size:18px">CONTACT FORM</strong></td>
      </tr>
      <tr align="center" bgcolor="#0088cc">
        <td colspan="2" bgcolor="#ffa500">Fields with * are required.</td>
      </tr>
 
      <tr>
        <td width="85">First Name:</td>
        <td>
          <input name="firstname" type="text" size="55" maxlength="100" value="<?php echo $_POST["firstname"]; ?>"> *
          <?php  if(isset($errFirstName)) echo $errFirstName; ?>
        </td>
      </tr>
      <tr>
        <td>Last Name:</td>
        <td>
          <input name="lastname" type="text" size="55" maxlength="100" value="<?php echo $_POST["lastname"]; ?>">
          <?php  if(isset($errLastName)) echo $errLastName; ?>
        </td>
      </tr>
      <tr>
        <td>Company Name:</td>
        <td>
          <input name="companyname" type="text" size="55" maxlength="100" value="<?php echo $_POST["companyname"]; ?>">
          <?php  if(isset($errCompanyName)) echo $errCompanyName; ?>
        </td>
      </tr>
      <tr>
        <td>Address:</td>
        <td>
          <input name="address" type="text" size="55" maxlength="100" value="<?php echo $_POST["address"]; ?>">
          <?php  if(isset($errAddress)) echo $errAddress; ?>
        </td>
      </tr>
      <tr>
        <td>Postal Code:</td>
        <td>
          <input name="postalcode" type="text" size="12" maxlength="5" value="<?php echo $_POST["postalcode"]; ?>">
          <?php  if(isset($errPostalCode)) echo $errPostalcode; ?>
        </td>
      </tr>
      <tr>
        <td>Phone:</td>
        <td>
          <input name="phone" type="text" size="14" maxlength="15" value="<?php echo $_POST["phone"]; ?>">
          <?php  if(isset($errPhone)) echo $errPhone; ?>
        </td>
      </tr>
      <tr>
      <tr>
        <td>Fax:</td>
        <td>
          <input name="fax" type="text" size="14" maxlength="15" value="<?php echo $_POST["fax"]; ?>">
          <?php  if(isset($errFax)) echo $errFax; ?>
        </td>
      </tr>
      <tr>
        <td>Email:</td>
        <td>
          <input name="email" type="text" size="55" maxlength="100" value="<?php echo $_POST["email"]; ?>"> *
          <?php  if(isset($errEmail)) echo $errEmail; ?>
        </td>
      </tr>
      <tr>
      <tr>
        <td>Subject:</td>
        <td>
          <input name="subject" type="text" size="55" maxlength="100" value="<?php echo $_POST["subject"]; ?>"> *
          <?php  if(isset($errSubject)) echo $errSubject; ?>
        </td>
      </tr>
      <tr>
        <td>Comment:</td>
        <td>
          <textarea name="comment" id="comment" cols="42" rows="7" value="<?php echo $_POST["comment"]; ?>"></textarea> *
        </td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>
          <input type="submit" name="Submit" value="Submit">
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <input type="reset" name="reset" style="color:#cc0000" value="Reset">
        </td>
      </tr>
 
    </table>
  </form>
  </center>
  </body>
</html>
 
<?php
};
?> 
 
Boco
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: PHP form validation and post sending

Post by social_experiment »

I rewrote the file a bit, hope it helps.
Attachments
Untitled-2.rar
(1.91 KiB) Downloaded 15 times
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
dboco
Forum Newbie
Posts: 5
Joined: Thu Feb 11, 2010 4:19 pm
Location: Slovenia

Re: PHP form validation and post sending

Post by dboco »

I really sincerely apologize for my late reply, social_experiment.

I noticed that your code really is different because it does not print out the error fields in the form below of those fields.

I am attracted to minor irregularities in the functioning of the form.
In the event that the email address is correct, the other required fields do not (such as name, that contains a number) or even empty,
send the form, what is wrong.

Could be done so that the error occurred in the form itself, for example at the bottom of the form?

On the other hand, the solution is cool and I thank you for such a speedy solution to my problem!

Sincerely,
Boco
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: PHP form validation and post sending

Post by social_experiment »

In the event that the email address is correct, the other required fields do not (such as name, that contains a number) or even empty, send the form, what is wrong.
No, the first check is for empty fields. If you enter just a valid format email address, you are refered to an empty page, which display a message about the empty fields. The page is only blank because in the stylesheet your body's color is set to white. If you run the page, view the source. The message should be visible then.

Here is an updated script. Hope it helps.
Attachments
Untitled-5.rar
(2.29 KiB) Downloaded 21 times
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
dboco
Forum Newbie
Posts: 5
Joined: Thu Feb 11, 2010 4:19 pm
Location: Slovenia

Re: PHP form validation and post sending

Post by dboco »

As I mentioned, by right completed required field for the email box and typed incorrectly field, such as name, send the form as it is all right.

For example:
Name: Tiger5 that is WRONG input, right is Tiger without numbers
Email: eee@eee.ee OK input
Subject: eeeeeeee OK input
Comment:eeeeeeeee OK input

it sents form successfully, what is wrong.

I looked at the code, but the if sentence looks good to me, so that I do not know what to be wrong.



In addition I would like to, that you repair if sentences, if it can be as follows:

First Name: (for example: Tiger or Anna Marie)
from letters, at least two
can contain letters a-z, A-Z, č, Č, ć, Ć, đ, Đ, š, Š, ž, and Ž
can contain white space
must begin with a capital
It CAN NOT BE an empty field


Last Name: (for example: Sanders or Bonham Carter)
from letters, at least two
can contain letters a-z, A-Z, č, Č, ć, Ć, đ, Đ, š, Š, ž, and Ž
can contain white space
must begin with a capital
It CAN BE an empty field


Company: (for example: LG or 3M or J2TV or AT&T or McDonald's or Wal-Mart or Yahoo! )
from letters
can contain letters a-z A-Z č Č ć Ć đ Đ š Š ž and Ž, at least one letter and one or more from other character from bellow
can contain the numbers
can contain the white spaces
can contain . , - _ & ' ! ? @
It CAN BE an empty field


Address: (for example: 2101 MASSACHUSETTS AVE NW or Hammersmith bridge road 216, London)
from letters
can contain letters a-z A-Z č Č ć Ć đ Đ š Š ž and Ž, at least two letter and one or more from other character from bellow
can contain the numbers
can contain the white spaces
can contain . ,
It CAN BE an empty field


Postal Code: (for example: 2101)
numbers only in the form of 0000 exactly 4 digits
It CAN BE an empty field


Phone and Fax:
Only numbers and spaces in the form (00) 000 00 00
or
Only numbers and spaces in the form 000000000 exactly 9 digits
It CAN BE an empty field


Email:
can contain all characters in the form a@a.aaa
or
ca contain all characters in the form a.a.a@a.aaa.aa
It CAN NOT BE an empty field


Subject: (for example: My 1. order, could be done?!)
from letters
can contain letters a-z A-Z č Č ć Ć đ Đ š Š ž and Ž, at least one letter and one or more from other character from bellow
can contain the numbers
can contain the white spaces
can contain . , - _ & ' ! ?
must begin with a capital
It CAN NOT BE an empty field


Comment:
can contain all characters at least two and not more than a three hundred
must begin with a capital
It CAN NOT BE an empty field



Sincerely,
Boco
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: PHP form validation and post sending

Post by social_experiment »

My honest opinion about the restrictions you are placing upon input from your form is that you are more likely to attract visitors that will attempt to test the limits of your system and see if they can break it. Experience tells me that if you tell a person "Don't do this", the odds are that they will attempt it. Attempting to filter out unwanted characters from specific fields (like numeric values from a 'name' field) is an exercise in futility and you should rather concentrate on making the input that you do receive safe enough by using functions such as addslashes(), trim(), htmlentities(). If you really MUST have these precautions in a form, limit them to something like a secondary form with the first form being a simple one indicating basic information such as a name, contact number and / or email address, so that when you contact this individual with a follow-up email, and they do respond, you know that you have a person that is showing some interest and is not just testing your patience and wasting your time. This all might seem rather irrelevant (and beyond the scope of this thread) but it points to having a submission form that is easy to fill out, without leaving the user fuming at their keyboard for not being able to meet intricate patterns for each of the fields.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
dboco
Forum Newbie
Posts: 5
Joined: Thu Feb 11, 2010 4:19 pm
Location: Slovenia

Re: PHP form validation and post sending

Post by dboco »

Yes, I fully agree with you entirely, social_experiment.
I just wanted to someone not play with filling out the form just because of boredom,
I also wish to prevent robots to fill the form for spam.

Sincerely
Boco
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: PHP form validation and post sending

Post by social_experiment »

I just wanted to someone not play with filling out the form just because of boredom,
I also wish to prevent robots to fill the form for spam.
You will always have people with too much free time on their hands, for something like that you could add to the script an IP logging feature so if you do receive a lot of spam from a certain address (or group of addresses) you have somewhere to start and some information to give to your webserver administrator (or if you needed to match up visitor logs, etc). As for the robots, i think you can add a check box that needs to be ticked before the email can be sent. :)
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
dboco
Forum Newbie
Posts: 5
Joined: Thu Feb 11, 2010 4:19 pm
Location: Slovenia

Re: PHP form validation and post sending

Post by dboco »

As for the robots, i think you can add a check box that needs to be ticked before the email can be sent. :)
Well, I will try with a check box with questionton, for example: Are you sure you want to send the form?
I hope to be able to do so. Can I contact you if I fail?

Regards,
Boco
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: PHP form validation and post sending

Post by social_experiment »

Yes, you can send me a pm and i'll help you where i can :)
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply