PHP Contact Form

In this tutorial, we are having a contact form to let the user send their queries, clarifications, feedback and more details. After submitting this form, we can access these details from a PHP page. Contact Form is one among the most commonly used form interface in web applications like registration, login, search and more.


Create Contact Form Interface

We have four fields as name, email, subject and content in our contact form. And the code is,

<title>Contact Us Form</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<form name="frmContact" method="post" action="">
<div class="message"><?php if(isset($message)) { echo $message; } ?></div>
<table border="0" cellpadding="10" cellspacing="1" width="500" align="center">
<tr class="tableheader">
<td colspan="2">Enter Contact Information</td>
<tr class="tablerow">
<td>Name<br/><input type="text" name="userName"></td>
<td>Email<br/><input type="text" name="userEmail"></td>
<tr class="tablerow">
<td colspan="2">Subject<br/><input type="text" name="subject" size="73"></td>
<tr class="tablerow">
<td colspan="2">Content<br/><textarea name="content" cols="60" rows="6"></textarea></td>
<tr class="tableheader">
<td align="center" colspan="2"><input type="submit" name="submit" value="Submit"></td>

We have included an external CSS which includes contact form styles.

.tableheader {
background-color: #95BEE6;
.tablerow {
background-color: #A7D6F1;
.message {
color: #FF0000;
font-weight: bold;
text-align: center;
width: 100%;

Read Contact Form Input from PHP

On submit the contact form, the PHP page will access contact form input by using PHP request methods $_GET or $_POST as specified in the form method.

$name = $_POST["userName"];
$email = $_POST["userEmail"];
$subject = $_POST["subject"];
$content = $_POST["content"];

Handling Contact Form Input

In PHP page we can either send these form input to a database table or we can send it to a mailbox.

Sending Contact Form Input to Email

Let our target mail id as The From Name and From Email is set to the mail header. And then, PHP mail function is used to send the contact mail to the admin. The code is,

$toEmail = "";
$mailHeaders = "From: " . $_POST["userName"] . "<". $email .">\r\n";
if(mail($toEmail, $subject, $content, $mailHeaders)) {
$message = "Your contact information is received successfully";

Store Contact Form Input into Database

First, we need to create a database table. And then, we should configure the database for getting its access to store contact form data from our PHP page.

$conn = mysql_connect("localhost","root","");
mysql_query("INSERT INTO tblcontact (user_name, user_email,subject,content) VALUES ('" . $name. "', '" . $email. "','" . $subject. "','" . $content. "')");

After executing above insert query, the contact data will be added to the database table as,


This PHP code tutorial was published on July 17, 2013.

↑ Back to Top