PHP email contact form

Soldato
Joined
4 Sep 2003
Posts
4,428
Location
Cornwall
Hi guys.

Firstly, I promise I have searched for this, but haven't been able to get far with what I found.

I'm a complete web design noob, in need of a very simple PHP form with which people can contact me from my website.

Name, Email, Subject, Message fields are all I need.

Could one of you kind souls talk me through it in single-syllable words please :p
 
Surely this has been asked a trillion billion times - if not here, on Google! Anyway here's some help - although I don't have time to step-by-step, it would be good from a learning point of view to figure it out from this..:

A few topics to learn:
- HTML Forms
- POST vs GET
- PHP POST variables (how to access those variables)
- PHP Mail() function (how to send an email using php)
- How to open a gmail account (because testing mail scripts primarily on hotmail is setting sail for fail)

;)

Basicly; HTML Form "posts" form details to a PHP page, PHP page uses the contents of POST variables, and uses those variables to send an email to you. If you have a HTML field with its name set to "comments", when the user presses submit it posts to another page (your php page). In the code for that php page, you can access the comments using $_POST['comments']. You'll want to use $_POST['comments'] in the body of your mail.

Once you've got your head around that you might want to move onto some other mail class rather than php's own. You might also want to read about mail injection if you're feeling up to it.
 
Right.. First off, we need to create our form..

Code:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>King4aDay's Form</title>
<style type="text/css">
<!--
body
{
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10px;
}
-->
</style>
</head>

<body>
<form action="" method="post">
<table cellspacing="3" cellpadding="3" border="0">
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" id="subject" /></td>
</tr>
<tr>
<td>Message:</td>
<td><textarea name="message" id="message" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="button" id="button" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>

Code:
<style type="text/css">
<!--
body
{
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10px;
}
-->
</style>

This is basically our style for the page. We're setting the properties of the <body> tag with the following:

- Set the font to Verdana
- Set the font size to 10px

Simple enough so far :P

Code:
<form action="" method="post">
<table cellspacing="3" cellpadding="3" border="0">
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" id="subject" /></td>
</tr>
<tr>
<td>Message:</td>
<td><textarea name="message" id="message" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="button" id="button" value="Submit" /></td>
</tr>
</table>
</form>

Ok, this is the main body of the form.. We encase the form fields etc within a table. This is so that we can line everything up and make it look a lot neater :P

Note that I have named each individual form field with its own name and id - This is so that we can refer to them later when we come to coding the PHP!

Code:
<form action="" method="post"></form>

Ok so we have surrounded our table with the above form tags. Basically what this is saying is, we want the form to submit using the POST method. This is the opposite to GET which shows the variables within the URL (i.e index.php?name=Adam). The reason I have left the 'action' field blank is because we want the form to submit to the same page it is on as it gives a more professional feel if everything is on one page.

One last thing, take note of your button's name, as we will need to use this in order to check if the form has been submitted!

Ok so now we have the form, we can concentrate on our PHP..

We put the PHP right at the top of the page, before the <html> tags.

So to start, we need to state that we will be coding in PHP.. to do this, we use the following tags:

Code:
<?php ?>

Ok, so now we've told the page we will be coding in PHP, let's start coding!

Right, here is the PHP for your script (coded by myself :D):

PHP:
<?php
if($_POST['button']) // Check to see if the submit button has been pressed
{
    	if($_POST['name'] == "" or $_POST['email'] == "" or $_POST['subject'] == "" or $_POST['message'] == "") // Check to see if any fields have been left blank
        {
        	echo "You left a field blank!"; // Show 'You left a field blank!' on the screen
        }
        else // If the user hasnt entered any blank fields, then..
        {
        	$email = "[email protected]"; // Set the email address
            $subject = $_POST['subject']; // Set the subject as $subject
            
            $message = "Name: " . $_POST['name'] . "<br />"; // Set out how we want our message to be displayed in the $message variable. (Note: .= means append/add on to)
            $message .= "Subject: " . $_POST['subject'] . "<br />";
            $message .= "Email: " . $_POST['email'] . "<br /><br />";
            $message .= "Message: " . $_POST['message'];
            
            $headers  = 'MIME-Version: 1.0' . "\r\n"; // Set our HTML email headers
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
			$headers .= 'From: King4aDay\'s Form'; // Set who the email is shown to be from
            
            $mail = mail($email, $subject, $message, $headers); // Email!
            if(!$mail) // If the script could not email, then..
            {
            	echo "Email could not be sent! Please try again.."; // Tell the user!
            } else { // Else, if the script emailed successfully, then..
            	echo "Thank you! We will respond as soon as we can!"; // Congratulate the user that they have been l33t and sent an email.. :)
            }
        }
}
?>

Ok, I have commented the code so you should be able to understand it..

Here is the full thing.. save it as 'email.php' or whatever you want to call it!

Code:
<?php
if($_POST['button'])
{
    	if($_POST['name'] == "" or $_POST['email'] == "" or $_POST['subject'] == "" or $_POST['message'] == "")
        {
        	echo "You left a field blank!";
        }
        else
        {
        	$email = "[email protected]"; // Your email goes here
            $subject = $_POST['subject'];
            
            $message = "Name: " . $_POST['name'] . "<br />";
            $message .= "Subject: " . $_POST['subject'] . "<br />";
            $message .= "Email: " . $_POST['email'] . "<br /><br />";
            $message .= "Message: " . $_POST['message'];
            
            $headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
			$headers .= 'From: King4aDay\'s Form';
            
            $mail = mail($email, $subject, $message, $headers);
            if(!$mail)
            {
            	echo "Email could not be sent! Please try again..";
            } else {
            	echo "Thank you! We will respond as soon as we can!";
            }
        }
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>King4aDay's Form</title>
<style type="text/css">
<!--
body
{
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10px;
}
-->
</style>
</head>

<body>
<form action="" method="post">
<table cellspacing="3" cellpadding="3" border="0">
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" id="subject" /></td>
</tr>
<tr>
<td>Message:</td>
<td><textarea name="message" id="message" cols="45" rows="5"></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="button" id="button" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>

I hope that helps! I'm not really very good with tutorials :P

EDIT: This is a simplified example that I rustled up.. If I was coding for myself I would have coded this a bit more complex, but as it's only for learning purposes I left that out :)
 
Last edited:
Captcha...

Insert following into contact form page.
Code:
<img src="include/CaptchaSecurityImages.php?width=100&height=40&characters=5" />

<input id="security_code" name="security_code" type="text" />

put following in a folder called 'include'

PHP:
<?php
session_start();



class CaptchaSecurityImages {

	var $font = 'monofont.ttf';

	function generateCode($characters) {
		/* list all possible characters, similar looking characters and vowels have been removed */
		$possible = '23456789bcdfghjkmnpqrstvwxyz';
		$code = '';
		$i = 0;
		while ($i < $characters) { 
			$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
			$i++;
		}
		return $code;
	}

	function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
		$code = $this->generateCode($characters);
		/* font size will be 75% of the image height */
		$font_size = $height * 0.75;
		$image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
		/* set the colours */
		$background_color = imagecolorallocate($image, 255, 255, 255);
		$text_color = imagecolorallocate($image, 20, 40, 100);
		$noise_color = imagecolorallocate($image, 100, 120, 180);
		/* generate random dots in background */
		for( $i=0; $i<($width*$height)/3; $i++ ) {
			imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
		}
		/* generate random lines in background */
		for( $i=0; $i<($width*$height)/150; $i++ ) {
			imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
		}
		/* create textbox and add text */
		$textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
		$x = ($width - $textbox[4])/2;
		$y = ($height - $textbox[5])/2;
		imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
		/* output captcha image to browser */
		header('Content-Type: image/jpeg');
		imagejpeg($image);
		imagedestroy($image);
		$_SESSION['security_code'] = $code;
	}

}

$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '6';

$captcha = new CaptchaSecurityImages($width,$height,$characters);

?>

Then in the php file that processes the mail, add the following:

PHP:
session_start();

if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
		// Insert you code for processing the form here, e.g emailing the submission, entering it into a database. 
		unset($_SESSION['security_code']);
   } else {
		// Insert your code for showing an error message here
		die ('Sorry, you have provided an invalid security code');
   }

You will also need to add the text file monofont.ttf to your 'include' folder.
 
Back
Top Bottom