Skip to main content

How to Create an Email Contact Form in PHP

By SamK
0 recommends
Email Contact Form in PHP

Every website needs a contact form for visitor interaction. In this tutorial, we'll learn how to create an email contact form in PHP.

This form will send an email to the website contact email address after the form submission. 

To begin, create a file named "contact.php" with the following code:

<!DOCTYPE html>
		<title>Email Contact Form</title>
		<link rel="stylesheet" type="text/css" href="style.css"/>

	<div id="contact_form">
	<form name="contact" id="contact-form" method="post" action="contact.php">
		<input type="text" placeholder="Your Name" name="name" required />
		<input type="email" placeholder="Your Email" name="email" required />
		<input type="text" placeholder="Subject" name="subject" required />
		<textarea name="message" placeholder="Your message" required></textarea>
		<input type="submit" name="submit" class="form-submit" value="Contact Us" />

This form has three fields. You can add additional fields as well. You can see that this form is posting the submitted data to the same page via "action="contact.php" code. To capture these values after any user submits this form, we'll need some PHP code. Here is the corresponding PHP code:


if (isset($_POST['email'])) {
	// Get values from the form
	$name = $_POST['name'];
	$email = $_POST['email'];
	$subject = $_POST['subject'];
	$message = $_POST['message'];
	// Receipient's data
	$to = '';
	$subject = 'Contact Form Submission';
	$message = 'Name: ' . $name . '\r\n E-mail: ' . $email . '\r\n Subject: ' . $subject . '\r\n Message: ' . $message;
	// Sender's data
	$from = '';
	$headers = 'From:' . $from . "\r\n";
	$headers .= 'Content-type: text/plain; charset=UTF-8' . '\r\n';
	$success = mail($to,$subject,$message,$headers);
	// Show message based on success or failure
	if($success) {
  		echo '<div class="success-message">Email sent successfully.</div>';
	} else {
  		echo '<div class="error-message">Some error occurred! Please try again.</div>';


In this code, the PHP's mail() function is used to send emails. Save this code in the contact.php file after the opening <body> tag. Your PHP email contact form is ready to use now! You can also download the complete code with CSS styling below.