3 Files Used:
Requirements:
In this tutorial you will learn how to create a stylized form in HTML, code the backend in PHP to send an email to a specific address, and finally add a moderate Captcha system to thwart spammers from maliciously using your form.
We’ll start this off with a simple HTML template, that you are likely all too familiar with:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html> <head> <title>Contact Form - YourWebsite.com</title> </head> <body> </body> </html>
We will be using a CSS layout to organize the information. To help keep things simple, we have used inline styling- but do feel free to make your own remote CSS file to further cut down on code count.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html> <head> <title>Contact Form - YourWebsite.com</title> </head> <body> <div style="width:650px;border-left:1px solid black;border-right:1px solid gray;margin:0px auto;overflow:hidden;"> <h1 style="background-color:#1c5665;color:white;padding:5px;text-align:center;margin-top:0px;">Contact Form - YourWebsite.com</h1> <div style="float:left;width:214px;border-right:1px solid gray;padding:5px;background-color:#f6f8f9;height:100%;"> <p align="right" style="padding:5px;">Name:</p> <p align="right" style="padding:5px;">Email Address:</p> <p align="right" style="padding:5px;">Comment/Suggestion:</p> </div> <div style="float:left;width:415px;padding:5px;"> <p><input type="text" name="name" style="border:1px solid #1c5665;padding:3px;margin-top:5px;"></p> <p><input type="text" name="email" style="border:1px solid #1c5665;padding:3px;margin-top:5px;"></p> <p><textarea cols="40" name="comment" rows="4" style="border:1px solid #1c5665;padding:3px;margin-top:5px;"></textarea></p> </div> <div style="clear:both;"> </div> <hr style="color:gray" /> <input type="submit" value="Submit Form" /> <input type="hidden" name="form_submitted" value="1"/> </form> <div style="width:650px;height:10px;background-color:#1c5665;"> </div> </div> </body> </html>
So far things should be fairly simple if you already have some knowledge about HTML and basic forms. One thing that seems to stump a lot of developers is the float property in CSS. To properly create a structured float, you will need four components: the wrapper, two or more sections of content that are using the float property, and finally a DIV that clears the float. You can see these, respectively, below:
<!--WRAPPER --> <div style="width:650px;border-left:1px solid black;border-right:1px solid gray;margin:0px auto;overflow:hidden;"> <!--FLOATED CONTENT 1 --> <div style="float:left;width:214px;border-right:1px solid gray;padding:5px;background-color:#f6f8f9;height:100%;"> (content) </div> <!--FLOATED CONTENT 2 --> <div style="float:left;width:415px;padding:5px;"> (content 2) </div> <!--CLEAR FLOAT --> <div style="clear:both;"> </div> </div>
And that’s it! The HTML form is done for now. Now let’s go on with sending the form contents to a specified email address.
We like to keep file count as small as possible, so we will be recycling the same file we just created to act as both the form and the file that processes the data to email the contents to your email address. We can do this with a simple IF structure in PHP.
You may have noticed this hidden value in the form we created:
This is going to allow us to see whether or not the user is submitting the form, or if they are filling it out. Since this is only true once the “Submit Form” button is clicked, we can use the following IF structure in conjunction:
<?php if ($_POST['form_submitted'] != '1') { # Form not submitted, show form } else { # Process script, form was submitted } ?>
To save you hassle, you can easily implement this selection structure by nesting in around the HTML:
<?php if ($_POST['form_submitted'] != '1') { # Form was not submitted, show form ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html> <head> <title>Contact Form - YourWebsite.com</title> </head> <body> <div style="width:650px;border-left:1px solid black;border-right:1px solid gray;margin:0px auto;overflow:hidden;"> ...[form contents]... </div> <?php } else if ($_POST[form_submitted] == 1) { ?> <?php # Code to send email goes here, since form was submitted ?> <?php } ?> </div> </body> </html>
Now, onto the email function! PHP developers can make use of the mail() function already included in the PHP language. This function takes four main parameters to function correctly. As you’ll see below, we can simply plug in the information we just got from the submitted form– and the function takes care of the rest.
// Send $to = 'yourname@yourdomain.com'; $subject = "Message from " . $_POST['name']; $message = $_POST['comment']; $headers = "From: " . $_POST['email'] . "\r\n" . "Reply-To: ".$_POST['name'] . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); echo "<html><body style='background-color:#ececec;'><div style='width:300px;border:1px dashed black;text-align:center;margin:0px auto;margin-top:200px;padding:20px;font-size:20px;background-color:white;'>Your comment has been sent! Thanks!</div></html>";
It looks like we would be done. But, wait- what about those dastardly spammers?
Some Captcha scripts are quite confusing; making use of many different technologies to provide the best possible protection against spam robots. Even though Captchas have been cracked, they are hard to do so- and certainly will cut out almost all of your spam, if not all of it completely.
In this example we are using a fairly secure Captcha system. First we are going to need a background image for our Captcha, which you can download via “Save As..” here:
Now we will have to create a captcha.php file to build the image we will be using via the GD Library. Follow the comments in the script to help get an understanding of how it works:
<?php session_start(); // Generate a Random String, Based On Time $md5 = md5(microtime() * mktime()); //We don't need a 32 character long string, let's trim it $string = substr($md5,0,5); // Use GD Library to make a PNG from a file $captcha = imagecreatefrompng("captcha.png"); // Set colors of lines with RGB colors $black = imagecolorallocate($captcha, 0, 0, 0); $line = imagecolorallocate($captcha,233,239,239); // The following creates random lines to help throw off a spam robot's ability to guess the string imageline($captcha,0,10,50,16,$black); imageline($captcha,40,11,64,29,$black); imageline($captcha,0,60,90,0,$black); //Write the string to the image imagestring($captcha, 5, 20, 10, $string, $black); // Use MD5 encryption on the key, and store it for a comparison test later $_SESSION['key'] = md5($string); // Print out the image header("Content-type: image/png"); imagepng($captcha); ?>
This script is really neat, considering the .PHP file is treated as a .PNG image if successfully executed. This way, we can simply call to the image from the form and have a dynamic image to test our users with!
Now let’s go back to our form and make some necessary changes, as seen in red words below. This is the final version of the script- enjoy!
<?php session_start(); if ($_POST['form_submitted'] != '1') { ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <html> <head> <title>Contact Form - YourWebsite.com</title> </head> <body> <div style="width:650px;border-left:1px solid black;border-right:1px solid gray;margin:0px auto;overflow:hidden;"> <h1 style="background-color:#1c5665;color:white;padding:5px;text-align:center;margin-top:0px;">Contact Form - YourWebsite.com</h1> <div style="float:left;width:214px;border-right:1px solid gray;padding:5px;background-color:#f6f8f9;height:100%;"> <form method="post"> <p align="right" style="padding:5px;">Name:</p> <p align="right" style="padding:5px;">Email Address:</p> <p align="right" style="padding:5px;">Comment/Suggestion:</p> </div> <div style="float:left;width:415px;padding:5px;"> <p><input type="text" name="name" style="border:1px solid #1c5665;padding:3px;margin-top:5px;"></p> <p><input type="text" name="email" style="border:1px solid #1c5665;padding:3px;margin-top:5px;"></p> <p><textarea cols="40" name="comment" rows="4" style="border:1px solid #1c5665;padding:3px;margin-top:5px;"></textarea></p> </div> <div style="clear:both;"> </div> <hr style="color:gray" /> <div style="width:325px; border:1px solid black;margin:0px auto;text-align:center;"> <p><img src="captcha.php" /></p> <div style="margin-top:-15px;"> Please enter the image text: </div> <div style="margin-top:-3px;margin-bottom: 4px;"> <input type="text" name="code" style="border:1px solid #1c5665;padding:3px;margin-top:5px;"> </div> <input type="submit" value="Submit Form" /> <input type="hidden" name="form_submitted" value="1"/> </form> </div> <div style="width:650px;height:10px;background-color:#1c5665;"> </div> <?php } else if ($_POST[form_submitted] == 1) { ?> <?php //Encrypt the posted code field and then compare with the stored key if(md5($_POST['code']) != $_SESSION['key']) { echo "It seems you entered an invalid Captcha key. Please go back and try again."; }else{ session_unset(); session_destroy(); // Send $to = 'yourname@yourwebsite.com'; $subject = "Message from " . $_POST['name']; $message = $_POST['comment']; $headers = "From: " . $_POST['email'] . "\r\n" . "Reply-To: ".$_POST['name'] . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); echo "<html><body style='background-color:#ececec;'><div style='width:300px;border:1px dashed black;text-align:center;margin:0px auto;margin-top:200px;padding:20px;font-size:20px;background-color:white;'>Your comment has been sent! Thanks!</div>"; } ?> <?php } ?> </div> </body> </html>
Note in particular that we are using the Session Unset and Session Destroy functions. Without them, you could refresh the page continually after you passed the Captcha test and send as much spam as you would like- – despite our efforts!
Our form is still missing several things. You will likely need to add form validation, such as checking to see if all fields were filled out. You may also tweak the Captcha system to your liking- which is a great way to get experience with the GD Library. You may also want to consider that not everyone can see or hear- and that the Captcha in its current state will prevent such users from sending you mail.
Problem in wamp: Notice: Undefined index: form_submitted in C:\wamp\www\PHP_Learning\contact_form_capta\contact.php on line 4
Hi Arifur,
I would highly recommend that you get your own web hosting. I have used WAMP before and it has proven to be unstable in many cases. It isn’t a good testing environment.
Also please check that you have the captcha.php, contact.php, and captcha.png files created and in the same directory. I duplicated the script shown in this tutorial and everything is working.
I will need more information about what caused the problem if you have further problems.
Thanks Zachary Schuessler
Well it’s working great for me! Tx for the help, I’ll be using this in my web development class tomorrow
Hi.
Im Very new to php,and I’m So Excited by your example. I can see the Image [captcha file], but the text it’s not showing. Please what caused the problem?
Kind Regards
Hi Nicholas,
Email me any screen-shots and code you have at admin@learnphponline.com and I’ll see if there is anything wrong in your setup. Also include any details about your Internet server, browser, and PHP version.
Thanks!
Great, simple captcha system you have. Thumbs up
Nicholas’ problem is coming from the fact that the string is made up of $md5 = md5(microtime() * mktime()); imagestring($captcha, 5, 20, 10, $string, $black); but you then go and use $string instead of $md5, even when corrected the string $md5 is too long to fit in the box. I took a section of it, 7 characters long, which fitted nicely in the rectange.
@Mark – Well spotted! For some reason this line of code was missing: //We don’t need a 32 character long string, let’s trim it $string = substr($md5,0,5);
It is now updated. Thanks a million for pointing this out. If you notice anything else let me know.
@Mark
Thank you for taking the time to fix this line of code THAT was missing .
@Zachary Schuessler Your form is very good, and smart example for me to learn PHP. All I need to do now is => some String manipulation. When a user enters details on the contact form to check and validate this data etc.
Once Again Thank you Thank you Very Much.
Kind Regards Nicholas
i also need to play the view of the php file not just show code. like w3schools.com they also show the preview of the site on internet
@shahid – There is a preview on the top of the page to show you what your outcome should look like. I believe that is sufficient in this case, but I will take your advice into consideration.
Very simple solution indeed ! Nice job !
While using hidden fields in if clauses, some servers show this error: Notice: Undefined index:…
You can fix it like this: if ( isset($_POST['form_submitted']) != ’1′ )
Regards, Ali
how to create select option tag in help of PHP script.
just wanting to know, when the form has been sent, is there a way so it gets sent to another page, eg. thankyou.html???
I tried your code. always give me this.
Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at /home/truedate/public_html/sfcone/Contact.php:1) in /home/truedate/public_html/sfcone/Contact.php on line 2
Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/truedate/public_html/sfcone/Contact.php:1) in /home/truedate/public_html/sfcone/Contact.php on line 2
Can you tell me how to fix? The session start is at the top. Thanks John
Everything seems to look good and work fine for me I just don’t get the email notification sent to my email. I have entered it in on html-contact-form.php at
$your_email =’myemail.com’;// <<=== update to your email address
what else do I need to do to get it to send the email?
Never mind…it is working now. I don’t know why.