A contact or feedback form is essential for almost every website — it lets visitors reach the site owner directly. This tutorial shows you how to build a simple PHP contact form that sends an email using PHP's built-in mail() function.
Step 1 — Create the HTML Form (contact.php)
This file contains the form fields shown to the user. On submit it posts to php_contact_form.php.
<html>
<body>
<form name="contact_form" method="post" action="php_contact_form.php">
<table>
<tr>
<td colspan="2"><b>PHP Contact Form</b></td>
</tr>
<tr>
<td>Subject</td>
<td><input name="sub" id="sub" type="text" size="75"></td>
</tr>
<tr>
<td>Name</td>
<td><input name="name" id="name" type="text"></td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" id="email" type="text"></td>
</tr>
<tr>
<td>Message</td>
<td><textarea name="msg" cols="60" rows="5" id="msg"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
Step 2 — Create the Mail Handler (php_contact_form.php)
This file reads the posted data and sends it to the site owner using mail().
<?php $subject = $_POST['sub']; $name = $_POST['name']; $from = $_POST['email']; $message = $_POST['msg']; $to = "[email protected]"; // replace with your email $send_email = mail($to, $subject, $message); if ($send_email) { echo "Your message was sent successfully!"; } else { echo "Error sending message — please try again."; } ?>
How It Works
$subject,$name,$from,$message— store form fields from$_POST.$to— the email address that will receive the contact messages.mail($to, $subject, $message)— sends the email using the server's mail function and returnstrueon success orfalseon failure.- A success or error message is displayed to the visitor accordingly.
Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.