Author Topic: Contact Form Tutorial  (Read 1728 times)

nuttycoder

  • New Member
  • *
  • Posts: 19
  • Karma: +0/-0
    • View Profile
    • http://www.nuttycoder.net
Contact Form Tutorial
« on: December 16, 2008, 07:55:08 PM »
Need a contact form for your site? This tutorial shows you how to create one.

This tutorial assumes you have a basic knowledge of PHP there are other tutorials on this site that explains some of the mechanics used here.

The contact form will be sent to your email address once the form is completed.

First we check that the form has been submitted:

Code: [Select]
<?php
//This code runs if the form has been submitted
if (array_key_exists('submit'$_POST))
{
?>

If the form has been submitted we check to make sure the fields are not empty and trim any white space.

We first check the name field We make sure the input is less then 3 but not more then 20 char actors using the function strlen (string length) if the char actors are less or more then specified then an error is set but its not printed out just yet.

Code: [Select]
<?php
// check fields are not empty
$name trim($_POST['name']);
if (
strlen($name) < 3) {
$error['name'] = 'Name Must be more then 3 charactors.';
}
if (
strlen($name) > 20) {
$error['name'] = 'Name Must be less then 20 charactors.';
}
?>

Then we check for a valid email address: At the very least the email must have a character at @ symbol and another character

Code: [Select]
<?php 
// check for valid email address
$email $_POST['email'];
$pattern '/^[^@]+@[^srn'";,@%]+$/';
if (!preg_match($pattern, trim($email))) {
  $error[] = 'Please enter a valid email address';
  } 
?>

We then check the message input section to make sure its been filled in the same way we checked the name field

Code: [Select]
<?php 
// check fields are not empty
$message trim($_POST['message']);
if (
strlen($message) < 3) {
$error['message'] = 'Message Must be more then 3 characters.';
}
?>

Now we make sure there’s no errors set and proceed if there are no errors if there is errors they will be printed above the form

Code: [Select]
<?php 
// if validation is okay then carry on
if (!$error ) { 
?>

If no errors set send the email. Change the email address to your email address you want to use to get the form details.

For the subject field I’ve typed in Contact for “.$_SERVER['HTTP_HOST'].” This will get the server address its come from like: http://www.example.com

The body is the form details this can be laid out any way you like to put text on a new line use (new line)

Addtionalheaders will include your email address so when you receive the email it will display your email address in the from field.

Lastly we check to see if the email has been sent using an if statement and if the email has been sent then we set the variable $sent to true.

We then close the brackets for validation and for submitted.

Code: [Select]
<?php 
//send email
$to "example@domain.com";
$subject "Contact for ".$_SERVER['HTTP_HOST']."";
$body "on ".date('M j, Y')." Information from contact form: Name: $name With the email address of $email Wrote this message: $message";
$additionalheaders "From: <example@domain.com> ";
$additionalheaders .= "Replt-To: example@domain.com";
if(
mail($to$subject$body$additionalheaders))
{
$sent true;
 }
 
// end valadation
}// end submit
?>

Once the email has been sent show a success message

Code: [Select]
<?php  
// If mail is sent
if (isset($sent)) {
 
echo 
"<p>Thank you </p>";
echo 
"<p>We will be in touch shortly </p>";
 
} else { 
// mail not sent show form
?>

if the email has not been sent and errors are set show the errors then display the form

Code: [Select]
<?php
echo "<p>Use this contact form for general enquires</p>";
echo 
"<p>I hate spam and I'm sure you do too, so don't worry your email address will <strong>NOT</strong> be passed on to any third party's </p>";
 
// show any errors if set
echo "<blockquote>";
if (isset(
$error['name'])) {
        echo 
"<p><span class="warning">".$error['name']."</span></p> ";
        }
 if (isset(
$error['email'])) {
        echo 
"<p><span class="warning">".$error['email']."</span></p> ";
        }
 if (isset(
$error['message'])) {
        echo 
"<p><span class="warning">".$error['message']."</span></p> ";
        }
echo 
"</blockquote>";
?>

Now we show the for. The form will reload the same page once its sent using

Code: [Select]
action="<?php echo $_SERVER['PHP_SELF']; ?>"
I’ve always set the form to be a sticky form so it there is an error the form keeps the inputted date using the value in the input field

Code: [Select]
<?php if(isset($error)) {echo "value='$name'";} ?>
After the form is finished we close the else statement that is still open

Code: [Select]
<?php ?>

<?php 
<form action="<?php echo $_SERVER['PHP_SELF']; ?>
" method="post">
<fieldset>
<legend>Contact</legend>
<p><label>Name:</label><input name="name" type="text" maxlength="20" <?php if(isset($error)) {echo "value='$name'";} ?> /></p>
 
<p><label> Email:</label>
<input name="email" type="text" maxlength="2550" <?php if(isset($error)) {echo "value='$email'";} ?> /></p>
 
<p><label>Message:</label>
<textarea name="message" cols="50" rows="10" id="message"><?php if(isset($error)) {echo $message;} ?></textarea>
</p>
 
<p><input type="submit" name="submit" value="Send Message"></p>
</fieldset>
</form>
<?php ?>

here is the full code:

Code: [Select]
<?php
//This code runs if the form has been submitted
if (array_key_exists('submit'$_POST))
{
 
// check fields are not empty
$name trim($_POST['name']);
if (
strlen($name) < 3) {
$error['name'] = 'Name Must be more then 3 characters.';
}
if (
strlen($name) > 20) {
$error['name'] = 'Name Must be less then 20 characters.';
}
 
// check for valid email address
$email $_POST['email'];
$pattern '/^[^@]+@[^srn'";,@%]+$/';
if (!preg_match($pattern, trim($email))) {
  $error[] = 'Please enter a valid email address';
  }
 
// check fields are not empty
$message = trim($_POST['message']);
if (strlen($message) < 3) {
$error['message'] = 'Message Must be more then 3 characters.';
}
 
// if validation is okay then carry on
if (!$error ) {
 
//send email
$to = "
example@domain.com";
$subject = "
Contact for ".$_SERVER['HTTP_HOST']."";
$body = "
on ".date('M j, Y')." Information from contact formName$name With the email address of $email Wrote this message$message";
$additionalheaders = "
From: <example@domain.com";
$additionalheaders .= "
Replt-Toexample@domain.com";
if(mail($to, $subject, $body, $additionalheaders))
{
$sent = true;
 }
 
} // end validation
}// end submit
 
 
// If mail is sent
if (isset($sent)) {
 
echo "
<p>Thank you </p>";
echo "
<p>We will be in touch shortly </p>";
 
} else { // mail not sent show form
 
echo "
<p>Use this contact form for general enquires</p>";
echo "
<p>I hate spam and I'm sure you do too, so don't worry your email address will <strong>NOT</strongbe passed on to any third party's </p>";
 
// show any errors if set
echo "<blockquote>";
if (isset($error['
name'])) {
        echo "<p><span class="warning">".$error['
name']."</span></p> ";
        }
 if (isset($error['
email'])) {
        echo "<p><span class="warning">".$error['
email']."</span></p> ";
        }
 if (isset($error['
message'])) {
        echo "<p><span class="warning">".$error['
message']."</span></p> ";
        }
echo "</blockquote>";
?>

 
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Contact</legend>
<p><label>Name:</label><input name="name" type="text" maxlength="20" <?php if(isset($error)) {echo "value='$name'";} ?> /></p>
 
<p><label> Email:</label>
<input name="email" type="text" maxlength="2550" <?php if(isset($error)) {echo "value='$email'";} ?> /></p>
 
<p><label>Message:</label>
<textarea name="message" cols="50" rows="10" id="message"><?php if(isset($error)) {echo $message;} ?></textarea>
</p>
 
<p><input type="submit" name="submit" value="Send Message"></p>
</fieldset>
</form>
<?php ?>
« Last Edit: January 06, 2012, 11:59:16 AM by jSherz »

Zyppora

  • Global Moderator
  • Senior Member
  • *****
  • Posts: 1401
  • Karma: +0/-0
    • View Profile
Re: Contact Form Tutorial
« Reply #1 on: December 19, 2008, 04:46:06 AM »
Additionally, in order to use the mail() function, an SMTP server is required to be set in your php.ini file. Most hosting providers have this enabled, but when you do devving on your own machine, this could be why your email is never sent ;)
HAVE YOU TRIED DEBUGGING? Example code in this reply deliberately contains BUGS. PHP forum for beginners.

nuttycoder

  • New Member
  • *
  • Posts: 19
  • Karma: +0/-0
    • View Profile
    • http://www.nuttycoder.net
Re: Contact Form Tutorial
« Reply #2 on: December 19, 2008, 05:12:39 AM »
yeah very good point, I've only used this on live hosts so I've never had that problem.

pbravo

  • New Member
  • *
  • Posts: 2
  • Karma: +0/-0
    • View Profile
Re: Contact Form Tutorial
« Reply #3 on: June 28, 2011, 07:26:40 AM »
Hello ... do you know about some free hosting with mail() function and SMTP server enable? I've been testing lots of free hostings thats supposed to had the mail() function on but none of them sends the contact form data to my email.