How to Create Simple Contact Form in PHP

In Previous article, we learn How to Create Contact Form using HTML CSS. Now, we'll learn How to Create Simple Contact Form in PHP. PHP is the most easy and common language for server side scripting. It has many features but in this article we'll discuss about its mailing function. How can be it used and implemented into contact form

There are two steps for backend connectivity. first is, we'll create contact form API that can handle and verify form data. Once its done we'll connect frontend and backend using Ajax. It is a part of JavaScript

Features:

  • Simple, Fast & Secure

Requirements:

  • PHP 4 or above+
  • HTML5
  • jQuery

Let's Start Coding:

Create a Contact PHP file named contact.php and follow steps:

To make sure our code protected and prevent from hacking, we'll create a function that accept all user input data and filter it.

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $field = array();
 foreach($_POST as $key => $value){
  $key = htmlentities(trim(utf8_encode(strip_tags($key))));
  $value = htmlentities(trim(utf8_encode(strip_tags($value))));
  $field[$key] = $value;
 }
 echo send_mail($field);
}

Explanation: In above code filter function used strip_tags(), utf8_encode(), trim(), htmlentities(). You can read more about them on official website of PHP.

Second Step is about to make send_mail() function which can send email to any Email ID.

function send_mail($fields){
    global $mail,$mail2;
    $m = '<html><head><title>'.$mail['subject'].'</title></head><body><table>';
    if(is_array($fields) && count($fields) > 0){
        foreach($fields as $key => $value){
            if(!$value){
                continue;
            }
            $m .= '
            <tr>
                <th align="left" valign="top">'.ucwords(str_replace(array('_','-'),' ',$key)).'</th>
                <th valign="top">:</th>
                <td valign="top">'.nl2br($value).'</td>
            </tr>
            ';
        }
    }
 $m .= '</table></body></html>';
 $mail['message'] = str_replace('{fields}',$m,$mail['message']);
 $to = explode(",",$mail['to']);
 $status = 0;
 foreach($to as $_to){
  $_to = strtolower($_to);
  if(!filter_var($_to,FILTER_VALIDATE_EMAIL)){
   continue;
  }
  if(mail($_to,$mail['subject'],$mail['message'],$mail['headers'],'-f'.$mail['from_mail'])){
   $status = 1;
  }  
 }
 if($status == 1 && $mail2['enable'] == 1){
  //send second mail
  $search = array();
  $replace = array();
  foreach($fields as $key => $value){
   $search[] = '{'.$key.'}';
   $replace[] = $value;
  }
  $mail2['to'] = str_replace($search,$replace,$mail2['to']);
  $mail2['subject'] = str_replace($search,$replace,$mail2['subject']);
  $mail2['message'] = str_replace($search,$replace,$mail2['message']);
  mail($mail2['to'],$mail2['subject'],$mail2['message'],$mail['headers'],'-f'.$mail['from_mail']);
 }
 return $status;
}
You can also make a separate file for all function and called that using require_once 'functions.php';

Next Step is set the Variables and Mail Header

$mail['to']   = 'contact@irahulsaini.com'; //replace with your email, multiple email id seperated by comma
$mail['from_name']  = 'Rahul Saini'; //replace with yours
$mail['from_mail']  = 'hello@irahulsaini.com'; //replace with yours
$mail['subject']  = "A New Contact Message Received";
$mail['message']  = '
<p><b>Details of sender:</b></p>
{fields}
- Thanks &amp; Regards
';

$mail2['enable'] = 1;
$mail2['to'] = '{email}';
$mail2['subject'] = 'Thanks for contacting us';
$mail2['message'] = '
<p>
 Dear {name},<br/>
 Thanks for Contacting us, our team will respond your message within 1-2 business days<br/>
<br/>
<b>- Thanks &amp; Regards</b><br/>
- Rahul Saini<br/>
<a href="mailto:hello@irahulsaini.com">hello@irahulsaini.com</a>
<a href="https://www.irahulsaini.com">www.weforit.com</a>
';

/*
 ******************************************
 ******** DON'T MODIFY CODE BELOW *********
 ******************************************
 */
/* Mail headers */
$mail['headers'][] = "MIME-Version: 1.0" . "\r\n";
$mail['headers'][] = "Content-type:text/html;charset=UTF-8" . "\r\n";
$mail['headers'][] = "From: ".$mail['from_name']." <".$mail['from_mail'].">"."\r\n";
$mail['headers'] = join('',$mail['headers']);
$mail is a primary variable that is used to send mail to owner and also stored PHP Mail header configuration/ $mail2 variable contain a confirmation email and it is optional.

That's it now we've backend scripting and next step is connect it to our HTML Form, To Do so we need JavaScript Ajax Method but before go ahead it require a small piece of code that handle Ajax request and give response.

Let's Take a look on Full PHP Code: