Web Design and Development Forums

PHP mail() --> Making a Form / Validating Input / Sending an email

This is a discussion on "PHP mail() --> Making a Form / Validating Input / Sending an email" within the PHP Forum section. This forum, and the thread "PHP mail() --> Making a Form / Validating Input / Sending an email are both part of the Program Your Website category.


Go Back   Webforumz.com > Program Your Website > PHP Forum

Welcome to Webforumz.com.
Register Now Register now!

Closed Thread
 
LinkBack Thread Tools Rate Thread
Old Oct 23rd, 2007, 07:06   #1 (permalink)
 
c010depunkk's Avatar
 
Join Date: Apr 2007
Location: Willich, Germany
Age: 20
Posts: 612
Blog Entries: 2
Send a message via MSN to c010depunkk
PHP mail() --> Making a Form / Validating Input / Sending an email

Here's a short tutorial on creating a form mail application using PHP.

Please read through this before posting any questions on this topic on the forums.
__________________
Web design is the creation of digital environments that facilitate and encourage human activity; reflect or adapt to individual voices and content; and change gracefully over time while always retaining their identity.

~ www.c010depunkk.com ~ the hang-out of a web developer


Last edited by c010depunkk; Oct 23rd, 2007 at 09:33.
c010depunkk is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Old Oct 23rd, 2007, 07:23   #2 (permalink)
 
c010depunkk's Avatar
 
Join Date: Apr 2007
Location: Willich, Germany
Age: 20
Posts: 612
Blog Entries: 2
Send a message via MSN to c010depunkk
Re: PHP mail() --> Making a Form / Validating Input / Sending a Mail

We'll start by making a simple HTML page:
HTML: Select all
<!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."
__________________
Web design is the creation of digital environments that facilitate and encourage human activity; reflect or adapt to individual voices and content; and change gracefully over time while always retaining their identity.

~ www.c010depunkk.com ~ the hang-out of a web developer


Last edited by c010depunkk; Oct 23rd, 2007 at 09:34.
c010depunkk is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Old Oct 23rd, 2007, 08:20   #3 (permalink)
 
c010depunkk's Avatar
 
Join Date: Apr 2007
Location: Willich, Germany
Age: 20
Posts: 612
Blog Entries: 2
Send a message via MSN to c010depunkk
Re: PHP mail() --> Making a Form / Validating Input / Sending a Mail

Now we'll continue 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.
PHP: Select all

// 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:
PHP: Select all

// 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:
PHP: Select all

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 Justin Timberlake wants to contact you and 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.'
PHP: Select all

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.
PHP: Select all

(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").
PHP: Select all

$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....
__________________
Web design is the creation of digital environments that facilitate and encourage human activity; reflect or adapt to individual voices and content; and change gracefully over time while always retaining their identity.

~ www.c010depunkk.com ~ the hang-out of a web developer


Last edited by c010depunkk; Oct 23rd, 2007 at 09:36.
c010depunkk is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Old Oct 23rd, 2007, 09:16   #4 (permalink)
 
c010depunkk's Avatar
 
Join Date: Apr 2007
Location: Willich, Germany
Age: 20
Posts: 612
Blog Entries: 2
Send a message via MSN to c010depunkk
Re: PHP mail() --> Making a Form / Validating Input / Sending a Mail

We now need to add some inline PHP to the HTML code:
HTML: Select all
<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:
PHP: Select all

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: Select all

<?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:
PHP: Select all

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.
PHP: Select all

if(!preg_match('/^([A-Z0-9._%-]+)@([A-Z0-9.-]+)\.([A-Z]{2,6})$/i',$value);) { 

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:
PHP: Select all

<?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.
PHP: Select all

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!
Good Luck with your project!
Feel free to post any questions....

EDIT: see post below for complete code.
__________________
Web design is the creation of digital environments that facilitate and encourage human activity; reflect or adapt to individual voices and content; and change gracefully over time while always retaining their identity.

~ www.c010depunkk.com ~ the hang-out of a web developer


Last edited by c010depunkk; Jan 17th, 2008 at 06:32. Reason: strange errors.....
c010depunkk is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Old Jan 17th, 2008, 06:35   #5 (permalink)
 
c010depunkk's Avatar
 
Join Date: Apr 2007
Location: Willich, Germany
Age: 20
Posts: 612
Blog Entries: 2
Send a message via MSN to c010depunkk
Re: PHP mail() --> Making a Form / Validating Input / Sending a Mail

OK, for some reason, when you copy the code from the post, PHP throws errors at the IF statement on line 12....
No clue what that is all about.

I've attached a PHP file with the complete code. I've tested this file and it works!
Attached Files
File Type: php form_mail.php (3.1 KB, 27 views)
__________________
Web design is the creation of digital environments that facilitate and encourage human activity; reflect or adapt to individual voices and content; and change gracefully over time while always retaining their identity.

~ www.c010depunkk.com ~ the hang-out of a web developer


Last edited by c010depunkk; Jan 17th, 2008 at 06:52.
c010depunkk is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit! Wong this Post!
Closed Thread

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Sending Form Data to E-mail Address Fools Gold New to Web Design 4 Dec 23rd, 2007 14:16
sending form info to email eon201 PHP Forum 2 Oct 26th, 2007 15:34
PHP email form not sending email Kurt PHP Forum 1 Oct 12th, 2007 04:26
Sending Form to E-mail student_in_training JavaScript Forum 2 Aug 16th, 2006 12:41
About sending form-data to an email address a.jenery HTML Forum 4 Mar 3rd, 2006 12:17



Latest Updates

All Points SEO Security Advisory - CHECK YOUR SITE NOW!

Creative Coding :: February 2008

Webforumz is sponsored by: WESH UK Web Hosting
All times are GMT. The time now is 05:48.

Sleep Study Scoring :: Free Bet :: Website Templates :: Online Betting :: Bookmakers :: Funny Quotes :: Internet Recruitment Software :: Microsoft CRM Experts :: Online Casino :: Decorated Christmas Trees :: Midwife Forums :: Football Betting :: Ecommerce Software :: Web Hosting :: Football Stats :: Dry Cleaning Collection :: xtreme wales - extreme clothing :: Apuestas :: Sharepoint Consultants :: Website Optimisation :: Office Clearance London :: Sharepoint Experts :: Sports Betting :: Casino :: Website Templates :: Web Design Development India :: Online Gambling

Powered by: vBulletin Version 3.7, Copyright ©2000 - 2008, Jelsoft Enterprises Limited.
© 2003-2008 Webforumz.com : All Rights Reserved
Search Engine Friendly URLs by vBSEO 3.2.0 RC6


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59