This script allows users to fill out a form on your website for support and the contents will be emailed to you. It’s a pretty basic feedback form handling script.
I think this is a pretty good email validation script.
The features are: 1. It uses exceptions so you can handle the errors in a centralized way.
I just echoed out the error message but you can do all kinds of stuff to handle the errors.
- This email validation script uses php’s built in filter, and validation functions, which simplifies the code
Please tell me if you see any security holes in this script, or just general suggestions on making it better will be welcome. Or if you like the script and think it works well, then please let me know. Thanks in advance.
I didn’t include the feedback form, but if you need it, just ask.
<?php
$_POST['fullname'] = 'John Smith'; //user name
$_POST['email'] = 'jsmith@example.com'; //user email address
$_POST['message'] = 'mary had a little lamb'; //user message
function mail_exception_handler($e)
{
echo $e->GetMessage();
}
set_exception_handler('mail_exception_handler');
$fullname = trim($_POST['fullname']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
$spam = trim($_POST['spam']);
if ($_POST) {
if (strlen($fullname) > 0) {
$clean_fullname = filter_var($fullname, FILTER_SANITIZE_STRING);
} else {
throw new Exception('Please enter your full name');
}
if (strlen($email) > 0) {
$clean_email = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($clean_email === FALSE) {
throw new Exception('Please enter a valid email');
}
} else {
throw new Exception('Please enter an email address');
}
if (strlen($message) > 0) {
$clean_message = filter_var($message, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
$clean_message = wordwrap($clean_message, 70);
} else {
throw new Exception('Please enter your message');
}
if (strlen($spam) > 0) {
//spam is a hidden form field that is left blank
//if the spam field is filled, it is likely being filled by a robot
throw new Exception('An error has occurred in sending your message');
}
} else {
throw new Exception('Please complete all fields in the email form'); //if nothing is submitted throw this exception
}
//Send the Message
if (isset($clean_fullname, $clean_email, $clean_message)) {
define(TO, 'info@xyz.com'); //your email address
$subject = 'XYZ Incorporated';
$message = 'On ' . date('l dS \\of F Y h:i:s A') . ' ' . $clean_fullname . ' wrote,' . "\
\
\
" . $clean_message;
$headers = 'From:' . $clean_email . "\\r\
" . 'Reply-To:' . $clean_email . "\\r\
" . 'X-Mailer: PHP/' . phpversion();
$mail = mail(TO, $subject, $message, $headers);
var_dump($mail);
echo 'Thank you for choosing XYZ com';
}
?>