Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL
PHPBasicsCreating a ScriptRunning a ScriptVariablesExpressions and OperatorsStringsStrings and SubstringsReplacing SubstringsRegular ExpressionsBranches and ConditionsLoopsArraysArray FunctionsSorting ArraysUser-Defined FunctionsInclude and RequireUploading FilesFile FunctionsSession Variables
Recommended Reading
PHP and MySQL web development

programming PHP

PHP cookbook

Home > PHP Tips and Tricks > Form Reply Scriptsprinter version

PHP Form Reply Scripts

A form reply requires two things. An HTML form to gather user input as name/value pairs and a PHP script to receive the data and place it in an email and send it.

The HTML Form

Below is a simple form that gathers two name/value pairs, email and comments, and passes them to form_reply.php when the user clicks the Send button.

A Simple Form Example
<form action="form_reply.php" method="post">
    Your email address:
    <input type="text" size="50" maxlength="75" name="email">
    Your comments:
    <textarea rows="4" cols="30" name="comments">
    </textarea>
    <input type="submit" name="Send">
</form>


The PHP Script

The name/value pairs are passed as an associative array called $HTTP_POST_VARS so we can use foreach to loop through the array and copy them into our own array called $formvars.

Gathering the Data
<?php
foreach($HTTP_POST_VARS as $varname => $value)
    $formvars[$varname] = $value;
?>


Cleaning the Input

Whenever you have any kind of form on your site that accepts input to be processed by a PHP script there is a rule that should never be broken.

Never trust user input. Never rely solely upon HTML size attributes or JavaScript event handlers to screen or limit user input.

These are easily circumvented since they run on the client side, where the mischief-makers have control, and not the server side where you have control.

All user input should be cleaned using PHP string functions to screen out dangerous characters and to limit size before being used by the rest of the script.

To clean the data we can create a function that will remove any characters that might be used to create spam, escape any mischievious shell commands and limit the size of the input.

We can also use the trim() function to remove leading and trailing whitespace and tab characters etc.

A Clean Function
<?php
function clean($input, $maxlength)
{
    $input = str_replace("'", "&#39;", $input);
    $input = str_replace('"', '&#34;', $input);
    $input = str_replace("\\", "", $input);
    $input = str_replace("Content-Type:", "", $input);
    $input = str_replace("\n", "", $input);
    $input = str_replace("\r", "", $input);
    $input = str_replace("%0a", "", $input);
    $input = str_replace("%0d", "", $input);
    $input = str_replace("bcc:", "", $input);
    $input = str_replace("to:", "", $input);
    $input = str_replace("cc:", "", $input);
    $input = substr($input, 0, $maxlength);
    $input = EscapeShellCmd($input);
    return ($input);
}
?>


Now the clean() and trim() functions can be used with foreach to clean each value before it's stored in the formvars array.

Cleaning and Storing the Data
<?php
function clean($input, $maxlength)
{
    $input = str_replace("'", "&#39;", $input);
    $input = str_replace('"', '&#34;', $input);
    $input = str_replace("\\", "", $input);
    $input = str_replace("Content-Type:", "", $input);
    $input = str_replace("\n", "", $input);
    $input = str_replace("\r", "", $input);
    $input = str_replace("%0a", "", $input);
    $input = str_replace("%0d", "", $input);
    $input = str_replace("bcc:", "", $input);
    $input = str_replace("to:", "", $input);
    $input = str_replace("cc:", "", $input);
    $input = substr($input, 0, $maxlength);
    $input = EscapeShellCmd($input);
    return ($input);
}

// Limit the size of each value to 1000 bytes
$size = 1000;
foreach($HTTP_POST_VARS as $varname => $value)
    $formvars[$varname] = trim(clean($value, $size));
?>


The PHP mail() Function

The sendmail() function accepts five string arguments, three are required and two are optional.



All that remains is to set up the arguments of the mail function then forward the user to a page that lets them know the email was sent.

Sending the email
<?php
// Set up e-mail address
$to = "info@somedomain.com";
// Setup the subject line
$subject = "Feedback from reply form:";
// Put together the body of the email
$message = "E-mail address: ".$formvars[email]."\r\n";
$message .= "Comments: ".$formvars[comments];
// Send the email
mail($to, $subject, $message);
// Forward the user to a thank you page
header("Location: thank_you.php");
?>


Note: You'll sometimes see a forwarding address being passed to a form script from a hidden field in an HTML form. This should be avoided because it can be changed to multiple addresses by a mischevious user to send spam.

Always try to hard code the forwarding address into your form script whenever possible.


The Complete Script
<?php
function clean($input, $maxlength)
{
    $input = str_replace("'", "&#39;", $input);
    $input = str_replace('"', '&#34;', $input);
    $input = str_replace("\\", "", $input);
    $input = str_replace("Content-Type:", "", $input);
    $input = str_replace("\n", "", $input);
    $input = str_replace("\r", "", $input);
    $input = str_replace("%0a", "", $input);
    $input = str_replace("%0d", "", $input);
    $input = str_replace("bcc:", "", $input);
    $input = str_replace("to:", "", $input);
    $input = str_replace("cc:", "", $input);
    $input = substr($input, 0, $maxlength);
    $input = EscapeShellCmd($input);
    return ($input);
}

// Limit the size of each value to 1000 bytes
$size = 1000;
foreach($HTTP_POST_VARS as $varname => $value)
    $formvars[$varname] = trim(clean($value, $size));

// Set up e-mail address
$to = "info@somedomain.com";
// Setup the subject line
$subject = "Feedback from reply form:";
// Put together the body of the email
$message = "E-mail address: ".$formvars[email]."\r\n";
$message .= "Comments: ".$formvars[comments];
// Send the email
mail($to, $subject, $message);
// Forward the user to a thank you page
header("Location: thank_you.php");
?>



Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
Tips and TricksPage TemplatesPHP Form reply scriptsForm Reply ScriptsForm ValidationJavaScript to PHP
Got any PHP Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.