Simple e-mail form script
Posted: Fri Dec 04, 2009 12:14 pm
I am a VERY beginner PHP user but I am trying to create a simple but secure script for mailing from a contact form. It is working with one web hosting but not when I loaded it on another. So any suggestions on how to make it more secure or work better would be appreciated. I am trying to make it work for PHP 4 or 5 since that is what seems to be supported on most web hosts I work with. Here is my process form code:
Please be honest, I really am trying to learn. Sorry this is a very beginner question. Thanks!
Code: Select all
<?php
//set e-mail recipient
$myemail = "simpleaspen@gmail.com";
// Assign variables, check input, and give error message for required fields.
$name = check_input($_POST['name'], "Please enter your name.");
$email = check_input($_POST['email'], "Please enter a valid e-mail address.");
$mesg = check_input($_POST['message']);
$extra = check_input($_POST['extra']);
//If checkbox is chosen send 'yes', if not chosen send 'no'
if($_POST[newsletter]==""){
$nletter="no";
}else{
$nletter="yes";
}
//If e-mail is not valid show error message
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid. Please correct the e-mail address and resubmit.");
}
// Build the email (replace the address in the $to section with your own)
$to = "$myemail";
$subject = "River Rags Contact Form";
$mesg = "$name said:
$mesg
sign up for newsletter? $nletter";
$headers = "From: $email";
//honeypot field
if ($_POST["extra"] == "") {
// Send the mail using PHPs mail() function
mail($to, $subject, $mesg, $headers);
/* Redirect visitor to the thank you page */
echo('Thank you! Your message has been sent. Return to the<a href="http://www.riverragsdesigns.com"> River Rags Designs website</a>.');
exit();
}
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo "$myError <br />";
echo('Return to the<a href="http://www.riverragsdesigns.com/contact.html">River Rags Designs</a> contact form.');
?>
</body>
</html>
<?php
exit();
}
?>