Welcome Guest!

If you do not have an account yet on The Web Squeeze forums, please Register! It's FREE and there are many benefits:

  • Receive Fast Advice
  • Learn Programming Languages
  • Get Professional Website Reviews
  • Quick Troubleshooting Assistance

> Php Form Mail - C010depunkk's Version

This is a discussion on Php Form Mail - C010depunkk's Version, within the PHP section. This forum and the thread "Php Form Mail - C010depunkk's Version" are both part of the Programming Your Website category.

 
Closed TopicStart new topic
> Php Form Mail - C010depunkk's Version, a small tutorial on how to create an email form using PHP
c010depunkk
post Feb 21 2008, 09:36 AM
Post #1


Rapid Squeezer
Group Icon

Posts: 442
Joined: 14-February 08
From: Düsseldorf, Germany

In the next few posts I'll be presentin' a small tut on how to create an email form using PHP.

CONTENTS:
XHTML.
Validating user input.
the mail() function.

Here's the finished .php file for the eager ones:
Attached File  form_mail.php ( 3.14K ) Number of downloads: 21

I'd suggest reading throught the following posts....


--------------------
an umcomfortably attractive blend of sort of perverted but suprisingly sweet.
aggregated @ Re-Unleashed
I also tumble, tweet & flick
Go to the top of the page
 
+Quote Post
c010depunkk
post Feb 21 2008, 09:37 AM
Post #2


Rapid Squeezer
Group Icon

Posts: 442
Joined: 14-February 08
From: Düsseldorf, Germany

Here is the first post of the tutorial. We'll start by making a simple HTML page:
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>form mail</title>

<style type="text/css" media="all">
* { margin:0;padding:0; }
body { font:600 12px/22px verdana;padding:50px; }
.box, textarea, .button { border:2px solid #6699CC;font:inherit;color:inherit; }
.box { width:250px; }
textarea { width:300px;height:250px; }
.error { color:#DD1100; }
</style>

</head>

<body>

<div class="contact">
     <h1>Contact Us</h1>
     <p>Please fill out the form to contact us. Required fields are marked with a star [*].</p>
     <form name="contact" action="form_mail.php" method="post">
         <p>Name:* <input class="box" type="text" name="name" /></p>
         <p>E-Mail:* <input class="box" type="text" name="email" /></p>
         <p>Subject: <input class="box" type="text" name="subject" /></p>
         <p>Message:*</p><textarea name="message"></textarea>
         <p><input class="button" type="submit" action="submit" value="Send" />
     </form>
</div>

</body>

</html>

Save this code as "form_mail.php."


--------------------
an umcomfortably attractive blend of sort of perverted but suprisingly sweet.
aggregated @ Re-Unleashed
I also tumble, tweet & flick
Go to the top of the page
 
+Quote Post
c010depunkk
post Feb 21 2008, 09:39 AM
Post #3


Rapid Squeezer
Group Icon

Posts: 442
Joined: 14-February 08
From: Düsseldorf, Germany

Now we'll start by adding some user input validation. At the very top of form_mail.php add some PHP tags (<?php ?>) and then we can start coding.
The first thing we want to do is declare and initialize some variables that we will be using later in our script. The $required_fields array can be adjusted (for example, you could remove the 'email' field if you don't think it's necessary to know the email of the person contacting you. The $to_address variable should be changed to the email to which you want the contact requests to be sent to.
CODE
// declare and initialize some variables
   $name=$email=$subject=$message=$error_message='';
   $invalid_fields=array();
   $required_fields=array('name','email','message');
   $validated=array();
   $to_address='blub@bla.com'; // your email address goes here

The next chunk of code checks if anything was posted and validates the user input:
CODE
// validate $_POST array
   if(count($_POST)>0) { // was something posted?
       foreach($_POST as $key=>$value) { // loop through the $_POST array
           if(in_array($key,$required_fields)&&$value=='') { // check if a required field is empty
                // add that field to the $invalid_fields array
               array_push($invalid_fields,$key);
               // and append the error message to the $error_message variable
               $error_message.='<p>Please enter a'.(preg_match('/^[aeiouy]/',$key)?'n':'').' '.$key.'.</p>';
           }
           // field is not in the $invalid_fields array?
           if(!in_array($key,$invalid_fields)) {
               // copy it to the $validated array
               $validated[$key]=htmlspecialchars($value);
           }
       }
   } else { // make everything invalid so that the form is outputted and not the thankyou message
       $invalid_fields=$required_fields;
   }

Some explanations:

foreach($_POST as $key=>$value) { // loop through the $_POST array
This line lets us look at each index of the $_POST array. During each iteration, the value of the current index is stored in $value and the name of the current index is stored in $key. For example, when the user submits the form, the first value in the $_POST array would be $_POST['name'] == 'Justin Timberlake' so during the first iteration of the FOREACH loop, $key == 'name' and $value == 'Justin Timberlake.'

if(in_array($key,$required_fields)&&$value=='') { // check if a required field is empty
In this IF statement we check if the current value of $key is in the $required_fields array. If it is then we check if it is empty ($value == '') because a required field MUST contain a value.

(preg_match('/^[aeiouy]/',$key)?'n':'')
This little inline IF isn't really necessary, it just raises the usability. The regular expression checks to see if the value stored in $key starts with a vowel and if it does, "a" becomes "an" (ex: "a name" or "an email").

$invalid_fields=$required_fields;
If nothing was posted, we set the $invalid_fields equal to the $required_fields. I'll explain why in my next post....


--------------------
an umcomfortably attractive blend of sort of perverted but suprisingly sweet.
aggregated @ Re-Unleashed
I also tumble, tweet & flick
Go to the top of the page
 
+Quote Post
c010depunkk
post Feb 21 2008, 09:41 AM
Post #4


Rapid Squeezer
Group Icon

Posts: 442
Joined: 14-February 08
From: Düsseldorf, Germany

We now need to add some inline PHP to the HTML code:
CODE
<div class="contact">
     <h1>Contact Us</h1>
<?php
if(count($invalid_fields)<=0) { // send message / thank user
     // mail will get sent here
?>
     <p>Your message was successfully delivered.</p>
<?php } else { ?>
     <p>Please fill out the form to contact us. Required fields are marked with a star [*].</p>
     <?php echo(($error_message!=''?'<div class="error">'.$error_message.'</div>':'')); ?>
     <form name="contact" action="form_mail.php" method="post">
         <p>Name:* <input class="box" type="text" name="name" value="<?php echo($validated['name']); ?>" /></p>
         <p>E-Mail:* <input class="box" type="text" name="email" value="<?php echo($validated['email']); ?>" /></p>
         <p>Subject: <input class="box" type="text" name="subject" value="<?php echo($validated['subject']); ?>" /></p>
         <p>Message:*</p><textarea name="message"><?php echo($validated['message']); ?></textarea>
         <p><input class="button" type="submit" action="submit" value="Send" />
     </form>
<?php } ?>
</div>
Explanations:

if(count($invalid_fields)<=0) { // send message / thank user
Here we check if there are any invalid fields. If not, then we can send the email (still coming) and thank the user. Otherwise, we re-output the form. The valid values are outputted to the form, but the invalid entries are not.

<?php echo(($error_message!=''?'<div class="error">'.$error_message.'</div>':'')); ?>
Here we use an inline IF statement to check if the $error_message message variable contains something and if it does, then we output the error message to the user.

Some More Input Validation
Until now we have only checked to see if the required fields contained a value. You can get pretty paranoid about validating user input, but in this tutorial, we are just going to check if the email address has the correct format. To do this we need to modify the FOREACH loop:
CODE
foreach($_POST as $key=>$value) { // loop through the $_POST array
     if(in_array($key,$required_fields)&&$value=='') { // check if a required field is empty
          // add that field to the $invalid_fields array
         array_push($invalid_fields,$key);
         // and append the error message to the $error_message variable
         $error_message.='<p>Please enter a'.(preg_match('/^[aeiouy]/',$key)?'n':'').' '.$key.'.</p>';
     } else {
         switch($key) {
             case 'email': // validate email address format
                 if(!preg_match('/^([A-Z0-9._%-]+)@([A-Z0-9.-]+)\.([A-Z]{2,6})$/i',$value);) {
                     array_push($invalid_fields,'email');
                     $error_message.='<p>Please enter a valid email.</p>';
                 }
                 break;
         }
     }
     // field is not in the $invalid_fields array?
     if(!in_array($key,$invalid_fields)) {
         // copy it to the $validated array
         $validated[$key]=htmlspecialchars($value);
     }
}
Explanations:

We added an ELSE statement and a SWITCH so that for each index of the $_POST array, we can perform further validation. Here we are only going to validate the 'email' value, but you can perform further validations by adding CASES to the SWITCH.

if(!preg_match('/^([A-Z0-9._%-]+)@([A-Z0-9.-]+)\.([A-Z]{2,6})$/i',$value)wink.gif {
There are hundreds of regular expressions that can be used to validate an email format. This is one of the simplest and most effective ones I've come across (from http://www.regularexpressions.info) If the entered email doesn't match this regex, then we add 'email' to the $invalid_fields array and append an error message.

Sending the EMail
So, now we've validated the user input and once the user has entered all the necessary information correctly, we can send the email:
CODE
<?php
if(count($invalid_fields)<=0) { // send message / thank user
     $formatted_message='When: '.date('r').'
Who: '.$name.' ('.$email.')
With What: '.$_SERVER['HTTP_USER_AGENT'].'
Message: '.$message;
     mail($to_address,$subject,$formatted_message);
?>
Explanations:

First we format the message a bit...: When --> get the date and time that the message was sent. Who --> the name and email supplied by the user. With What --> which browser the user used to contact us (I always find this interesting ). Message --> and the user's message.

mail($to_address,$subject,$formatted_message');
Configuring your server so that the mail() function works is too complicated to explain here. I'm just going to assume that it works.... The required parameters are $to_address (where the email is headed), $subject (the subject of the email) and $formatted_message (the body of the email).

FINISHED!
Here is the finished form_mail.php:
CODE
<?php
/****** PHP Form Mail *****/

// declare and initialize some variables
$name=$email=$subject=$message=$error_message='';
$invalid_fields=array();
$required_fields=array('name','email','message');
$validated=array();
$to_address='blub@bla.com'; // your email address goes here

// validate $_POST array
if(count($_POST)>0) { // was something posted?
     foreach($_POST as $key=>$value) { // loop through the $_POST array
         if(in_array($key,$required_fields)&&$value=='') { // check if a required field is empty
              // add that field to the $invalid_fields array
             array_push($invalid_fields,$key);
             // and append the error message to the $error_message variable
             $error_message.='<p>Please enter a'.(preg_match('/^[aeiouy]/',$key)?'n':'').' '.$key.'.</p>';
         } else {
             switch($key) {
                 case 'email': // validate email address format
                     if(!preg_match('/^([A-Z0-9._%-]+)@([A-Z0-9.-]+)\.([A-Z]{2,6})$/i',$value)) {
                         array_push($invalid_fields,'email');
                         $error_message.='<p>Please enter a valid email.</p>';
                     }
                     break;
             }
         }
         // field is not in the $invalid_fields array?
         if(!in_array($key,$invalid_fields)) {
             // copy it to the $validated array
             $validated[$key]=htmlspecialchars($value);
         }
     }
} else { // make everything invalid so that the form is outputted and not the thankyou message
     $invalid_fields=$required_fields;
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>form mail</title>

<style type="text/css" media="all">
* { margin:0;padding:0; }
body { font:600 12px/22px verdana;padding:50px; }
.box, textarea, .button { border:2px solid #6699CC;font:inherit;color:inherit; }
.box { width:250px; }
textarea { width:300px;height:250px; }
.error { color:#DD1100; }
</style>

</head>

<body>

<div class="contact">
     <h1>Contact Us</h1>
<?php
if(count($invalid_fields)<=0) { // send message / thank user
     $formatted_message='When: '.date('r').'
Who: '.$name.' ('.$email.')
With What: '.$_SERVER['HTTP_USER_AGENT'].'
Message: '.$message;
     // send the email
     mail($to_address,$subject,$formatted_message);
?>
     <p>Your message was successfully delivered.</p>
<?php } else { ?>
     <p>Please fill out the form to contact us. Required fields are marked with a star [*].</p>
     <?php echo(($error_message!=''?'<div class="error">'.$error_message.'</div>':'')); ?>
     <form name="contact" action="form_mail.php" method="post">
         <p>Name:* <input class="box" type="text" name="name" value="<?php echo($validated['name']); ?>" /></p>
         <p>E-Mail:* <input class="box" type="text" name="email" value="<?php echo($validated['email']); ?>" /></p>
         <p>Subject: <input class="box" type="text" name="subject" value="<?php echo($validated['subject']); ?>" /></p>
         <p>Message:*</p><textarea name="message"><?php echo($validated['message']); ?></textarea>
         <p><input class="button" type="submit" action="submit" value="Send" />
     </form>
<?php } ?>
</div>

</body>

</html>
Good Luck with your project!
Feel free to post any questions....


--------------------
an umcomfortably attractive blend of sort of perverted but suprisingly sweet.
aggregated @ Re-Unleashed
I also tumble, tweet & flick
Go to the top of the page
 
+Quote Post
If you found The Web Squeeze to be helpful, please donate so we can keep this site FREE, FRESH, and fortified with Web Design & Development info!
Closed TopicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Collapse

> Similar Topics

    Topic Title Replies Topic Starter Views Last Action
No New Posts   9 caminowebmaster 1,194 15th February 2008 - 06:24 PM
Last post by: Jacob
No New Posts   3 craig 1,053 15th February 2008 - 01:51 PM
Last post by: thesealportalteam
No New Posts 12 xkatx21x 2,749 28th February 2008 - 11:41 PM
Last post by: Rakuli
No New Posts   4 thesealportalteam 3,683 20th February 2008 - 09:00 AM
Last post by: thesealportalteam
No new   14 902 2,961 22nd February 2008 - 02:45 AM
Last post by: c010depunkk