How to easily create a simple PHP Email Form
If <form action=”mailto: example@me.com”> simply isn’t cutting it anymore, it might be time to implement a PHP form, and from a design and usability perspective, users would much rather send a message directly from your website than their email client (most of us don’t even use an email client). Plus, if you have no prior experience with PHP, we break everything down for you. Let’s get coding!
Step 1 - The HTML
<form method=”post” action=”contact.php”>Email Address: <input name=”email” type=”text”><br> Message:<br> <textarea name=”message” rows=”5” cols=”60”></textarea><br> <input type=”submit”> </form>
If you’re familiar with HTML forms, you’ll recognize the form action and input types. What you probably have never seen before is form method=”post”. When a visitor clicks submit, this collects the user’s email address and message. It is then passed through “contact.php” where it’s sent to your predefined email. You with me so far?
Step 2 - The PHP
<?php $to = “example@me.com”; $subject = “New Message”; $email = $_REQUEST[‘email’] ; $message = $_REQUEST[‘message’] ; $headers = “From: $email”; $sent = mail($to, $subject, $name, $message, $headers) ; if($sent) {print “Thanks for your message. We’ll get back to you soon.”; } else {print “Hold the phone! There seems to be a problem sending your message.”; } ?>
This PHP file simply defines the email address where all submissions should be sent. In an effort to go a little further, it formats the email for you. Let’s break this down further. When a user submits a message, $_REQUEST grabs the data entered into the form moments earlier. Then, the message is formatted into something you and your email client will be able to understand. If sent correctly, a message of sucess will appear. If something went wrong, a message of failure will appear.
Step 3 - Getting it Working
Now that you have an understanding about what the code does, let’s get it working. The PHP code should be saved in a seperate file called, “contact.php”. You’ll then want to upload it to your website and copy down the location of the it on your server.
IMPORTANT: In order for your contact form to function correctly, your hosting service must support PHP on their servers. Also, if you forget to save with the .php file extension, your form will be useless.
After you have your PHP file uploaded, open your HTML file and replace “contact.php” with the location of the PHP file on your server. Save it as an HTML document and then upload. Finally, test it to make sure it works properly. Congratulations, if you’ve followed these instructions correctly, you have a new PHP contact form for your website.