Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Create a Simple PHP Contact Form

INTRODUCTION
KEEPING THINGS SIMPLE

Welcome to a beginner’s tutorial on how to create a simple PHP contact form. Are you looking for ways to add a contact form to your website? Send the contact form out by email? Well, it is actually a very simple process, but some people just tend to complicate it too much. Not in this guide, where we will start with the raw basics, and slowly build up to create “a nicer form” – Read on to find out!

I have included a zip file with all the example source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
No-Fluff Starter

Section B
Better Version

Section C
AJAX Version

Extra
Useful Bits

Extra
Source Code Download

Closing
What’s Next?

SECTION A
NO-FLUFF STARTER VERSION

First, let us get started with a very simple, raw basic version of the contact form.

STEP 1) THE HTML FORM

1-form.html


  
    
      Simple Contact Form Demo
    

CONTACT US

Yep – No surprises here, this is just a common Joe HTML form. A quick recap for those who might have forgotten the basics:

  • Captain Obvious – A form is defined with the
    tag.
    • The action attribute specifies which script will handle the processing of this form.
    • The method attribute can either be post or get.
    • Difference between them is that get will show all the form data in the URL, for example, https://site.com/2-email.php?c-name=John+Doe&[email protected]… Not very pleasant, which is why we use post to silently submit the data instead.
  • We sandwich and fields inside the
    tags, feel free to add more of your own as required.
    • The type attribute specifies what kind of field it is. A few of the common ones are – text, email, number, password, hidden, tel, button, submit.
    • The name attribute must be unique, and that is how we know which-is-which in PHP later.
    • Adding a required attribute will make sure that the user will enter something, or the form will not submit.
  • Finally a submit button at the bottom of the form.

STEP 2) PHP MAILER

2-email.php

Believe it or not, that’s all to the PHP script… Guess it does not need much explanation here.

  • We can get all the submitted form data in the $_POST global variable. Remember the name attributes that we defined in the HTML  fields earlier?
  • Format the email message nicely, and just use the mail() function to send it out.
  • Done.

SECTION B
A BETTER VERSION

Now that you know how the basic mechanics work, let us build a better version, add some salt-and-pepper to make things look more presentable.

STEP 1) THE HTML

3-form.html


  
    
      Simple Contact Form Demo
    

CONTACT US

Fret not. This is essentially still the same HTML form as above, with only 2 improvements:

  • Added some CSS styles, cosmetics to make the form look good. Feel free to change the styles to fit your own project theme.
  • Added minlength and maxlength to the input fields to further restrict the user input.

STEP 2) PHP MAILER

4-email.php
'
  // IF YOU NEED TO ADD CC
  // 'Cc: [email protected]'
];
$headers = implode("\r\n", $headers);

// SEND
if (@mail($to, $subject, $message, $headers)) {
  // OK
  header("Location: 5-thank-you.html");
} else {
  // ERROR
  header("Location: 6-error.html");
}
?>

Minor additions to this script as well –

  • Added email headers, where we can define the “email from”, and even add a “cc” field.
  • A slightly better way to deal with the process, just-in-case the email send fails.

STEP 3) PROPER FEEDBACK

Well, there is not much to this third step, we just create nice looking HTML pages to show the user on the process results.

5-thank-you.html


  
    
      Thank You!
    

Thank You!

We have received your contact query.

6-error.html


  
    
      Contact Form Error
    

Error

Error sending out email. Try again?

SECTION C
AJAX VERSION

Submitting the form will redirect the user to the PHP mailer script. So, what if we want an alternate version where the user will stay on the contact form page? We will have to use Javascript, and something called AJAX – Asynchronous JavaScript and XML.

STEP 1) THE HTML

7-form.html


  
    
      Simple Contact Form Demo
    

CONTACT US

Yes… Same old form again, but a few small changes to take note in this alternative:

  • To make this HTML clean, the CSS and Javascript are moved to external files.
  • The
    element no longer has method and action
  • We use onsubmit to specify that a Javascript function will handle the processing instead.

STEP 2) THE CSS

8-theme.css
#conform {
  padding: 20px;
  max-width: 320px;
  font-family: arial;
  background: #f2f2f2;
  border: 2px solid #ccc;
}
#conform h1 {
  margin: 0;
  padding: 0;
}
#conform label, #conform input, #conform textarea {
  box-sizing: border-box;
  width: 100%;
  display: block;
}
#conform label, #conform input[type=submit] {
  margin-top: 20px;
}
#conform label {
  color: #555;
}
#conform input[type=text], #conform input[type=email], #conform textarea {
  padding: 5px;
}
#conform input[type=submit] {
  padding: 10px;
  background: #486891;
  border: 0;
  color: #fff;
  font-size: 1em;
  cursor: pointer;
}

Same CSS as above… Except that we moved it into a separate file.

STEP 3) THE JAVASCRIPT

9-ajax-form.js
function conform() {
  // APPEND FORM DATA
  var data = new FormData();
  data.append('c-name', document.getElementsByName("c-name")[0].value);
  data.append('c-email', document.getElementsByName("c-email")[0].value);
  data.append('c-text', document.getElementsByName("c-text")[0].value);

  // INIT AJAX
  var xhr = new XMLHttpRequest();
  xhr.open('POST', "10-email.php", true);

  // WHEN THE PROCESS IS COMPLETE
  xhr.onload = function () {
    if (this.response=="OK") {
      // OK - Do something
      // Redirect user?
      // location.href = "5-thank-you.html";
      alert("OK");
    } else {
      // ERROR - Do something
      alert("ERROR");
    }
  };

  // SEND
  xhr.send(data);
  return false;
}

Confused? Well, if you look through the Javascript function, it really isn’t so bad:

  • We start by getting the form data from the HTML input fields.
  • Initiate AJAX, set to use the post method, and the target PHP script.
  • Set what to do when the AJAX process is complete with xhr.onload.
  • Finally, we just send the data out via AJAX. Take note – We need to return false to prevent the HTML form from submiting and reloading the page.

STEP 4) PHP MAILER

10-email.php
'
  // IF YOU NEED TO ADD CC
  // 'Cc: [email protected]'
];
$headers = implode("\r\n", $headers);

// SEND
if (@mail($to, $subject, $message, $headers)) {
  // OK
  echo "OK";
} else {
  // ERROR
  echo "ERROR";
}
?>

The same as above again, with the only exception that it will echo "OK" on success and echo "ERROR" on failure.

EXTRA
USEFUL BITS

That’s all for this tutorial, and here is a small section on some extras that may be useful to you.

REFERENCES

  • PHP Mail
  • HTML Form

PROBLEM SENDING OUT EMAIL?

Is the email not sending out on your computer or server? Check this out:

3 Ways to Fix PHP Mail Not Working

EXTRA
DOWNLOAD

Finally, here is the download link to the source code as promised.

SOURCE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post How to Create a Simple PHP Contact Form appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

How to Create a Simple PHP Contact Form

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×