How to Creat a Contact form in PHP
The HTML code of the form is given below:
In the contact form download, the form code is in the email-contact-form.html page. To embed the form in a web page, just copy and paste the HTML form code to the web page.
Validating the form submission
Form validations are essential for any web form. For this simple contact form, we will make all the fields mandatory and will make sure that the email field is in the format: name@xyz.com.
It is better to do validations both on the client side and on the server side. Client side validation provides a quick feedback to your visitor. However, the client side validation can just be bypassed by disabling JavaScript in the browser. Therefore, we need to validate on the server side as well.
For client side validation, we will use the Free JavaScript Form Validation Script. The script is very simple to use and has almost all validation types built-in.
Here is the client side form validation code:
Server-side processing
Once the contact form is submitted, the form submission data is sent to the script mentioned in the action attribute of the form (contact-form-handler.php in our form). The script then will collect the form submission data, validate it and send the email.
The first step is to validate the data. Ensure that the mandatory fields are filled-in, and that the email is in proper format.
The server-side code is given below:
$myemail = ‘yourname@website.com’;//if(empty($_POST[‘name’]) ||
empty($_POST[’email’]) ||
empty($_POST[‘message’]))
{
$errors .= “n Error: all fields are required”;
}
$name = $_POST[‘name’];
$email_address = $_POST[’email’];
$message = $_POST[‘message’];
if (!preg_match(
“/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i”,
$email_address))
{
$errors .= “n Error: Invalid email address”;
}
Emailing the form data using PHP
We will now compose and send the email.
{
$to = $myemail;
$email_subject = “Contact form submission: $name”;
$email_body = “You have received a new message. “.
” Here are the details:n Name: $name n “.
“Email: $email_addressn Message n $message”;
$headers = “From: $myemailn”;
$headers .= “Reply-To: $email_address”;
mail($to,$email_subject,$email_body,$headers);
//redirect to the ‘thank you’ page
header(‘Location: contact-form-thank-you.html’);
}
We first check whether the validations succeeded. If there were errors, the email is not sent. The PHP mail function is used to send the email. After sending the email, the visitor is redirected to the ‘thank you’ page.