How to create PHP Mail Form
Wednesday, January 04, 2006
Step 1: Create your formHere's the simple script:
<form action="process.php" method="post">
Name: <input type="text" name="name" size="20" maxlength="20"><br />
Email: <input type="text" name="email" size="30" maxlength="30"><br />
Subject: <input type="text" name="subject" size="30" maxlength="30"><br />
Text:<textarea name="text" name="text" cols="50" rows="10"></textarea><br />
<input type="submit" name="submit" value="Send">
</form>
Save this file as form.php.
You'll notice I used process.php as my form action. This is because the form data is going to be submitted to that file for actual mailing. I also wanted to limit how much data could be submitted. This is for security reasons.
Step 2: Processing the data
Now create a file called process.php.
First you want to get all the variables that were just sent to the page. Using the extract function, we can create identically named variables out of the $_POST array. In English this means that all the variables that have come to this page via the POST method (see the form above) will now be made into nice single-word variables.
@extract($_POST);
Now we want to make the data friendly for us.
$name = stripslashes($name);
$email = stripslashes($email);
$subject = stripslashes($subject);
$text = stripslashes($text);
Now we can do our mailing.
mail('youremail@domain.com',$subject,$text,"From: $name <$email>");
And finally redirect the user back to the form:
header("location:form.php");
So our code for process.php looks like this:
<?php
@extract($_POST);
$name = stripslashes($name);
$email = stripslashes($email);
$subject = stripslashes($subject);
$text = stripslashes($text);
mail('youremail@domain.com',$subject,$text,"From: $name <$email>");
header("location:form.php");
?>
There's plenty more you can do with mail().
see http://id2.php.net/mail for complete mail() function