Page 1 of 1

Newbie help with a form to email

Posted: Sun Apr 27, 2008 4:56 am
by mogsy
Hi,

I very new to PHP and need to add a PHP contact form scripty (on a seperate page from my form) thing to my website to stop spam mail injections and I thought at the same time I would have it flash up errors when required fields are empty (the fields being - name, details).

Does the following do what I need it to do and do you think the coding is alright? Any help or suggestions appreciated!

Code: Select all

<?php
 
// here, we check if the form has been submitted, because we need to handle
// redirection before we handle outputting the HTML stuff.
if (empty($_POST['name']) || empty($_POST['enquiry'])) {
   // here, they have not filled in either theyre name or enquiry details.  Set an error.
   die("Please fill in all required form fields.");
}
else
// Pick up the form data and assign it to variables
$title = $_POST['title'];
$name = $_POST['name'];
$email = $_POST['email'];
 
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
    die("Please enter a valid email address");
}
 
 
$phone = $_POST['phone'];
$address = $_POST['address'];
$heard_from = $_POST['heard_from'];
$heard_other = $_POST['heard_other'];
$style = $_POST['style'];
$material = $_POST['material'];
$deliveryrequired = $_POST['deliveryrequired'];
$enquiry = $_POST['enquiry'];
 
// Build the email (replace the address in the $to section with your own)
$to = 'me@mydomain.co.uk';
$subject = "Contact form enquiry";
$message = "Title:$title,
 
Name:$name,
 
Phone:$phone,
 
Address: $address,
 
Heard from: $heard_from,
 
Heard other: $heard_other,
 
Style: $style,
 
Material: $material,
 
Delivery required: $deliveryrequired,
 
Enquiry details: $enquiry,";
$headers = "From: $email";
 
// Send the mail using PHPs mail() function
// succe=false or true; = return values from mail() function
$succe = mail($to, $subject, $message, $headers);
 
// Redirect
if($succe)
{
    header("Location: confirmation.htm");
    exit(); // make sure to end php; just in case, a good habbit ..
}
else
{
    // end php, with a message of failure
    exit("Sorry. Mail was not sent. Go Back, try again");
}
?>