Seems a little basic but it works, thoughts? I'm not sure about sending multiple mail at once, I'm sure there is a better way to do it
Validation class
class Validation
{
private static
$contact,
$email,
$subject,
$message;
const MIN_NAME = 2,
MIN_SUBJECT = 1,
MIN_MESSAGE = 20;
public static function testName($contact){
//test contact me name
return(strlen($contact) >= self::MIN_NAME);
}
public static function testEmail($email){
//test email address
return (filter_var($email, FILTER_VALIDATE_EMAIL) != self::$email);
}
public static function testSubject($subject){
//test contact me subject
return(str_word_count($subject) >= self::MIN_SUBJECT);
}
public static function testMessage($message){
//test contact me subject
return(str_word_count($message) >= self::MIN_MESSAGE);
}
}
Sending mail
<?php
require ("classes/Validation.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$contact = $email = $subject = $message = "";
$contact = $post['contact'];
$email = $post['email'];
$subject = $post['subject'];
$message = $post['message'];
$errors = array();
$fields = array(
'contact' => array(
'validator' => 'testName',
'message' => 'Your name should be a minimum of two characters and alphanumeric'
),
'email' => array(
'validator' => 'testEmail',
'message' => 'Please enter a valid email address'
),
'subject' => array(
'validator' => 'testSubject',
'message' => 'Please enter at least one word for your title'
),
'message' => array(
'validator' => 'testMessage',
'message' => 'Please enter a minimum of twenty words'
)
);
foreach($post as $key => $value)
{
if(isset($fields[$key]))
{
if(!Validation::{$fields[$key]['validator']}($value))
{
$errors[] = ['name' => $key, 'error' => $fields[$key]['message']];
}
}
}
if(empty($errors))
{
try
{
//To user
$success = ["message" => "Your message was sent"];
$to = $post['email'];
$message = 'Thank you for getting in touch, I will be in contact soon!';
$message = wordwrap($message, 70, "\r\n");
$headers = 'From: no-reply@gotsocial.co.uk' . "\r\n" .
'Reply-To: no-reply@gotsocial.co.uk' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
$mailResult = mail($to, 'Email confirmation from cluelessPHP', $message, $headers);
//to me
$name = $contact = $post['contact'];
$from = $post['email'];
$topic = $subject = $post['subject'];
$send = 'xx@example.com';
$messages = wordwrap($message . "\n Sent by " . $name . "\n Reply to \n" . $email, 70, "\r\n");
$headers = 'From: no-reply@gotsocial.co.uk' . "\r\n" .
'Reply-To: no-reply@gotsocial.co.uk' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
$mailResult = mail($send, ". " . $topic, $messages, $headers);
}
catch(Exception $e)
{
$errors[] = ["name" => "email", "error" => "Your message was not sent"];
}
}
header('Content-Type: application/json');
if (empty($errors))
{
echo json_encode($success);
}
else
{
echo json_encode(["errors" => $errors]);
}
}