Contact Form
Posted: Mon Nov 01, 2010 1:54 pm
Hello,
I have used the below process code for years and now I am looking to improve it and improve security etc.
I have a couple of questions:
* Is it better to validate in JS or PHP?
* How Could I Improve This Script To Avoid Spammers or XSS Attacks?
This is only my minimal code. I have another one that processes value="<? value" of the check boxes etc.
I am just going around in circles trying to google etc.
I have used the below process code for years and now I am looking to improve it and improve security etc.
I have a couple of questions:
* Is it better to validate in JS or PHP?
* How Could I Improve This Script To Avoid Spammers or XSS Attacks?
This is only my minimal code. I have another one that processes value="<? value" of the check boxes etc.
I am just going around in circles trying to google etc.
Code: Select all
<?php
session_start();
if (!empty($_POST['validation']) && strlen($_POST['validation'])==10){
$subject = "Website Contact";
//print_r($_POST); die();
$required_fields = array('name', 'email','message'); // added 'checkbox' for required.
foreach($_POST as $key => $value) {
$_SESSION[$key] = trim($value);
if(in_array($key, $required_fields) && empty($value)) $errors[$key] = ucwords($key) .' is required!';
}
// make sure a valid email address is entered.
if(!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $_SESSION['email'])) {
$errors['email'] = 'A Valid email address is required!';
}
if(!$errors) {
$message = $_SESSION['subject'] ."\n\n";
$message .= "Name: ". $_SESSION['name'] ."\n\n";
$message .= "E-Mail: ". $_SESSION['email'] ."\n\n";
$message .= "Message: ". wordwrap ($_SESSION['message']) ."\n\n";
$message .= "\n\n";
$message .= date('j/m/Y g:ia');
$headers = "From:" . $_SESSION['name'] ." <". $_SESSION['email'] .">\n";
$headers .= "Reply-To: ". $_SESSION['name'] ." <". $_SESSION['email'] .">\n";
$headers .= "Return-Path: ". $_SESSION['name'] ." <". $_SESSION['email'] .">\n";
$headers .= "Bcc: \n";
if(mail($to, $subject, $message,$headers)){
$errors['heading'] = "<p>Thank You, Your enquiry has been sent.</p>";
}else{
$errors['heading'] = "ERROR! There was a system error, Please send your enquiry again.";
}
}
}
$_SESSION['error'] = $errors;
header("Location: ../../contact.php");
die();
session_destroy ();
?>