PHP Contact Forms

So I was just putting up another PHP driven contact form for the “under construction” page on my Thunder Rock website, when I figured I should probably blog about this because I’ll probably need to reference this later.  Instead of copy pasting a bunch of stuff from other contact forms, I decided to make this form as easy as possible.

I made a very simple HTML5 landing page that can be seen at www.thunder-rock.com and I figured I’ll put in a small little contact form while I cook up some really neat stuff.

Here’s the simple form code:

[cc escaped=”true” lang=”html4strict”]

<aside>
<!–Contact Form Begin–>
<form method=”post” action=”send_email.php”>
<h5>Contact Us</h5>
<p class=”Dekar” style=”text-align:center; margin-top: -30px;”>303-500-6783</p>
First name:<br /><input type=”text” name=”fname”/><br />
Last name: <br /><input type=”text” name=”lname”/><br />
E-mail: <br /><input type=”email” name=”email”/><br />
Comments:<br /><textarea type=”comments” name=”comments”></textarea><br />
<input type=”submit” />
<p class=”Dekar” style=”text-align:center; “>Thank you <?php echo ” $fname ” ?>for your submission</p>
</form>
<!–Contact Form End–>
</aside>

[/cc]

I made a simple PHP script that declares variables for each field and stores the information.  I actually ended up looking at the W3CSchools site because I forget syntax frequently, but I didn’t copy paste the code and forgot a simple underscore!  It took me about 20 form submissions and tweaks to finally figure this out. >.<

Here’s the code for the mail part of the PHP file.

[cc escaped=”true” lang=”php”]

<?php

$sendto = “###@###.###”;
$subject = “Mail Submission from Thunder-Rock.com”;

$fname = $_REQUEST[‘fname’];
$lname = $_REQUEST[‘lname’];
$email = $_REQUEST[’email’];
$comments = $_REQUEST[“comments”];

$message = “First Name: $fname \nLast Name: $lname \nEmail: $email \nComments: $comments”;
$headers = “From: $email”;

mail($sendto,$subject,$message,$headers);

?>

[/cc]

Then I copy pasted the entire index code into the send_email.php. underneath this and made a fun little tweak to make a personal taste to the form.

[cc escaped=”true” lang=”html4strict”]

<p style=”text-align:center; “>Thank you <?php echo ” $fname ” ?>for your submission</p>

[/cc]

I added an echo statement and used the variable that I created at the beginning of the document to add a personal touch to the contact thank you message.  While this could probably be argued that I could have used AJAX to just update part of the page, it is just a landing page, and I’m more interested in working on the actual site.

I hope this helps anyone that is making simple PHP forms.  Good luck!

Read more about PHP functions here.