PHP is open source scripting language. It\'s widely used to develop web applications.  Home Web Programming PHP Contact Script
Your Ad Here

Contact Script


Contact ScriptAs you may have seen around the internet, most sites have a contact page ... and at some point or another you may have wanted one yourself. Well this tutorial aims to show you how to create your own contact form.

The first thing we need to do is set up our configuration file ... this will store your email address, email subject and error domain.

config.php

<?php

function SafeHTML($string) {
$string = stripslashes($string);
$string = htmlspecialchars($string);
return nl2br($string);
}

/*
The function 'SafeHTML' helps to protect you from being sent HTML emails via your contact form.

http://us2.php.net/manual/en/function.htmlspecialchars.php

* & (ampersand) becomes &
* " (double quote) becomes "
* ' (single quote) becomes '
*< (less than) becomes <
*> (greater than) becomes >
*/

function ValidateEmail($Email){
$result = ereg("^[^@ ]+@[^@ ]+.[^@ .]+$", $Email);
if ($result){
return true;
} else {
return false;
}
}

/*
The 'ValidateEmail' function checks to see if the email provided is that of the structure of a real email address (something@somewhere.com). It doesn't check if the email address is a REAL address ... it just checks the format.
*/

$ErrorDomain = "http://www.joe2torials.com/test4/contact.php?error=1";

/*
The '$ErrorDomain' variable stores the URL the browser should re-direct to should any errors be encountered. Whatever you change the URL to, make sure you keep '?error=1' at the end.
*/

$to = "Your Name<you@your-domain.com>";
$subject = "Contact Form";

/*
'$to' is your email address, where the form shall be sent to.
'$subject' is the subject of the email.
*/

?>

The next step is to create our form. In this tutorial I will have the basic 3 fields;

  • Name
  • Email Address
  • Questions / Comments

Very basic, but it'll do.

contact.php

<?php session_start();
$ses_id = session_id(); // DO NOT REMOVE THIS LINE!
$_SESSION['ses_id'] = $ses_id; // OR THIS ONE!
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="keywords" content="" />
<meta name="description" content="" />

<title>Contact Form</title>

<style type="text/css">
body {
margin: 0px;
padding: 100px;
background: #fafafa;
font-family: verdana, Arial, sans-serif;
font-size: 11px;
line-height: 18px;
}

#Wrapper {
margin: 0 auto;
padding: 10px;
width: 500px;
background: #fff;
border: 1px solid #999999;
}

fieldset {
margin: 0px;
padding: 0px;
border: 0px;
}

legend {
display: none;
}

input, textarea {
margin: 0px;
padding: 1px;
font-family: Courier, monospace;
font-size: 11px;
border: 1px solid #999999;
}

span.cursor {
cursor: pointer;
}

p#Error_msg {
color: red;
}
</style>
</head>
<body>

<div id="Wrapper">
<?php
$Error = $_GET['error'];
if(isset($Error)) {
echo '<fieldset><legend>Contact Form</legend>'."n";
echo '<form action="thank_you.php" method="post">'."n";
echo '<p><label for="name"><strong>Name :</strong></label><br />'."n";
echo '<input type="text" name="name" id="name" tabindex="1" size="40" value="'.$_SESSION['name'].'" /></p>'."nn";

echo '<p><label for="email"><strong>E-mail address :</strong></label><br />'."n";
echo '<input type="text" name="email" id="email" tabindex="2" size="40" value="'.$_SESSION['email'].'" /></p>'."nn";

echo '<p><label for="comment"><strong>Questions / Comments :</strong></label> (<span class="cursor" onclick="document.getElementById('comment').rows += 5;" title="Increase The Textarea">increase</span> >> <span class="cursor" onclick="document.getElementById('comment').rows -= 5;" title="Decrease The Textarea">decrease</span>)<br />'."n";
echo '<textarea cols="50" rows="5" name="comment" id="comment" tabindex="3">'.$_SESSION['comment'].'</textarea></p>'."nn";

echo '<p id="Error_msg">'.$_SESSION['errormsg'].'</p>'."nn";

echo '<p><input type="submit" name="submit" value="submit" class="submit" tabindex="4" /> <input type="reset" value="reset" class="submit" tabindex="5" /></p>'."n";
echo '</form>'."n";
echo '</fieldset>'."n";
} else {
?>
<fieldset><legend>Contact Form</legend>
<form action="thank_you.php" method="post">
<p><label for="name"><strong>Name :</strong></label><br />
<input type="text" name="name" id="name" tabindex="1" size="40" /></p>

<p><label for="email"><strong>E-mail address :</strong></label><br />
<input type="text" name="email" id="email" tabindex="2" size="40" /></p>

<p><label for="comment"><strong>Questions / Comments :</strong></label> (<span class="cursor" onclick="document.getElementById('comment').rows += 5;" title="Increase The Textarea">increase</span> >> <span class="cursor" onclick="document.getElementById('comment').rows -= 5;" title="Decrease The Textarea">decrease</span>)<br />
<textarea cols="50" rows="5" name="comment" id="comment" tabindex="3"></textarea></p>

<p><input type="submit" name="submit" value="submit" class="submit" tabindex="4" /> <input type="reset" value="reset" class="submit" tabindex="5" /></p>
</form>
</fieldset>
<?php } ?>
</div>

</body>
</html>

And for the last step, the page which will actually process all the data;

thank_you.php

<?php session_start();

include 'config.php';

$ses_id2 = session_id();
if(!$ses_id2 == $_SESSION['ses_id']) {
$ErrorMsg = 'Error, session ID mismatch.';
$_SESSION['errormsg'] = $ErrorMsg;
header('Location: '.$ErrorDomain.'');
exit();
}

$Name = $_POST['name'];
$Email = $_POST['email'];
$Comment = $_POST['comment'];

$_SESSION['name'] = $Name;
$_SESSION['email'] = $Email;
$_SESSION['comment'] = $Comment;

if (($Name == NULL) || ($Email == NULL) || ($Comment == NULL)) {
$ErrorMsg = 'Error, please make sure all fields are filled in.';
$_SESSION['errormsg'] = $ErrorMsg;
header('Location: '.$ErrorDomain.'');
exit();
}

if (!ValidateEmail($Email)) {
$ErrorMsg = 'Error, invalid email address supplied.';
$_SESSION['errormsg'] = $ErrorMsg;
header('Location: '.$ErrorDomain.'');
exit();
}

$time = time();
$datetime = date("D, M jS Y / g:ia", $time);
$ip = $_SERVER["REMOTE_ADDR"];
$message = '
<html>
<head>
<title>'.$subject.'</title>
</head>

<body>
<p><strong>Name:</strong> '.$Name.'</p>
<p><strong>E-mail:</strong> '.$Email.'</p>

<p><strong>Comment / Question:</strong></p>
<p>'.SafeHTML($Comment).'</p>

<p><strong>Sent on:</strong> '.$datetime.'</p>
<p><strong>Logged IP Address:</strong> '.$ip.'</p>
</body></html>';

$headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=iso-8859-1rn";
$headers .= "From: $emailrn";
mail($to, $subject, $message, $headers);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="keywords" content="" />
<meta name="description" content="" />

<title>Contact Form - Thank You</title>
<style type="text/css">
body {
margin: 0px;
padding: 100px;
background: #fafafa;
font-family: verdana, Arial, sans-serif;
font-size: 11px;
line-height: 18px;
}

#Wrapper {
margin: 0 auto;
padding: 10px;
width: 500px;
background: #fff;
border: 1px solid #999999;
}
</style>
</head>
<body>
<div id="Wrapper">

<h1>Thank You</h1>
<p>Thank you <?=$Name?>, your comment/question has been received. The following information has been sent;</p>
<p><strong>Name:</strong> <?=$Name?></p>
<p><strong>E-mail:</strong> <?=$Email?></p>
<p><strong>Comment / Question:</strong></p>
<p><?=SafeHTML($Comment)?></p>

</div>
</body>
</html>

Ok, so maybe now your looking at this code and you don't understand how it works. Allow me to go into detail.

Why have I told you not to remove two of the top lines in the contact form page?

$ses_id = session_id(); // DO NOT REMOVE THIS LINE!
$_SESSION['ses_id'] = $ses_id; // OR THIS ONE!

This is simple, recently there have been a vunerability with contact forms where members have been bypassing the actual form completely and sending mail VIA the processing page ... this leads to serious spamming. So we put session_id() into a session to carry onto the process page. session_id() is basically a random value each user is given on each visit to the page ... these are quite unique. We put the value into a session and carry it through to the process page for the following reason;

$ses_id2 = session_id();
if(!$ses_id2 == $_SESSION['ses_id']) {
$ErrorMsg = 'Error, session ID mismatch.';
$_SESSION['errormsg'] = $ErrorMsg;
header('Location: '.$ErrorDomain.'');
exit();
}

Here we grab the session_id() again, then we check to see if the current session from the process page matches that of the contact form page ... if you have sent mail via the form then they will of course match ... but if your bypassing the form and you try to send mail you won't be able to ... you'll get an error. Stopping all chances of automated spamming.

On the contact page, when you view it you'll see that the actual form is;

<fieldset><legend>Contact Form</legend>
<form action="thank_you.php" method="post">
<p><label for="name"><strong>Name :</strong></label><br />
<input type="text" name="name" id="name" tabindex="1" size="40" /></p>

<p><label for="email"><strong>E-mail address :</strong></label><br />
<input type="text" name="email" id="email" tabindex="2" size="40" /></p>

<p><label for="comment"><strong>Questions / Comments :</strong></label> (<span class="cursor" onclick="document.getElementById('comment').rows += 5;" title="Increase The Textarea">increase</span> >> <span class="cursor" onclick="document.getElementById('comment').rows -= 5;" title="Decrease The Textarea">decrease</span>)<br />
<textarea cols="50" rows="5" name="comment" id="comment" tabindex="3"></textarea></p>

<p><input type="submit" name="submit" value="submit" class="submit" tabindex="4" /> <input type="reset" value="reset" class="submit" tabindex="5" /></p>
</form>
</fieldset>

But, should the processing page encounter any errors then I'll send you back to this page with '?error=1' set and you'll see the other form;

echo '<fieldset><legend>Contact Form</legend>'."n";
echo '<form action="thank_you.php" method="post">'."n";
echo '<p><label for="name"><strong>Name :</strong></label><br />'."n";
echo '<input type="text" name="name" id="name" tabindex="1" size="40" value="'.$_SESSION['name'].'" /></p>'."nn";

echo '<p><label for="email"><strong>E-mail address :</strong></label><br />'."n";
echo '<input type="text" name="email" id="email" tabindex="2" size="40" value="'.$_SESSION['email'].'" /></p>'."nn";

echo '<p><label for="comment"><strong>Questions / Comments :</strong></label> (<span class="cursor" onclick="document.getElementById('comment').rows += 5;" title="Increase The Textarea">increase</span> >> <span class="cursor" onclick="document.getElementById('comment').rows -= 5;" title="Decrease The Textarea">decrease</span>)<br />'."n";
echo '<textarea cols="50" rows="5" name="comment" id="comment" tabindex="3">'.$_SESSION['comment'].'</textarea></p>'."nn";

echo '<p id="Error_msg">'.$_SESSION['errormsg'].'</p>'."nn";

echo '<p><input type="submit" name="submit" value="submit" class="submit" tabindex="4" /> <input type="reset" value="reset" class="submit" tabindex="5" /></p>'."n";
echo '</form>'."n";
echo '</fieldset>'."n";

This second form uses SESSIONS to show the error message of what went wrong during processing and if any data was entered into form it'll be back in the form due to the values of the form elements.

So what possible errors could we get?

if (($Name == NULL) || ($Email == NULL) || ($Comment == NULL)) {
$ErrorMsg = 'Error, please make sure all fields are filled in.';
$_SESSION['errormsg'] = $ErrorMsg;
header('Location: '.$ErrorDomain.'');
exit();
}

If any of the form fields were left empty ... this would cause an error.

if (!ValidateEmail($Email)) {
$ErrorMsg = 'Error, invalid email address supplied.';
$_SESSION['errormsg'] = $ErrorMsg;
header('Location: '.$ErrorDomain.'');
exit();
}

If the email provided isn't of valid syntax ... this would cause an error also.

If all goes well, the mail is sent.



Author's URL: Joseph Skidmore
Thank you for voting.
Rate this Materials:
Bad 
1 2 3 4 5 Excellent
print this page subscribe to newsletter subscribe to rss

Web programming � everything from the basics of visual design and architecture to the specifics of applications, graphics, and scripting. More Web Programming: Most Popular Materials | Fresh Materials | More PHP Tutorials at LearnPHP.org

Add comments to "Contact Script"

Only registered users can write comment

Reader's comments
comments bbg May 27, 2007 says:
Re: Contact Script
Where you able to find a solution to these errors?

georgepribac wrote:
A few problems with this script.
First of all there is an error in contact.php because on line 73 "comment" should be 'comment'.
In the same file you haven't defined error so this line has to go off: $Error = $_GET;
Also you should use >> instead of >>
What do you think? :?:
comments georgepribac September 04, 2006 says:
Contact Script
A few problems with this script.
First of all there is an error in contact.php because on line 73 "comment" should be 'comment'.
In the same file you haven't defined error so this line has to go off: $Error = $_GET;
Also you should use >> instead of >>
What do you think? :?: