Need Help with PHP Script

I am trying to setup a good PHPmail handling script for exported site forms using recaptcha and header injection protection. I am using HTML5 field required tags to validate, but do I need to check isset on them in the handling script as well? All fields in this form are required. Does anyone have any advice? I have this working but does it look pretty solid? Missing anything?

<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST'){

  if (isset($_POST['name'])) $sender_name = preg_replace("([\r\n])", "", $_POST['name']);
  if (isset($_POST['email'])) $sender_email = preg_replace("([\r\n])", "", $_POST['email']);
  if (isset($_POST['phone'])) $sender_phone = preg_replace("([\r\n])", "", $_POST['phone']);
  if (isset($_POST['message'])) $sender_message = preg_replace("([\r\n])", "", $_POST['message']);

  $formcontent="From: $sender_name \n Email: $sender_email \n Phone: $sender_phone \n Message: $sender_message";
  $recipient = "**** ADD RECIPIENT EMAIL ADDRESS ****";
  $subject = "Contact Form";

  $match = "/(bcc:|cc:|content\-type:)/i";
  if (preg_match($match, $sender_name) ||
      preg_match($match, $sender_email) ||
      preg_match($match, $sender_phone) ||
      preg_match($match, $sender_message)) {
    die("Header injection detected.");
  }

  $mailheader = "From: $sender_email \r\n";
  $mailheader .= "Reply-to: $sender_email\r\n";

  $response = $_POST["g-recaptcha-response"];

  $url = 'https://www.google.com/recaptcha/api/siteverify';
  $data = array(
    'secret' => '**** ADD YOUT SECRET KEY ****',
    'response' => $_POST["g-recaptcha-response"]
  );
  $options = array(
    'http' => array (
      'method' => 'POST',
      'content' => http_build_query($data)
    )
  );
  $context  = stream_context_create($options);
  $verify = file_get_contents($url, false, $context);
  $captcha_success=json_decode($verify);

  if ($captcha_success->success==false) {
    header('Location: failed.html');
    exit;
  } else if ($captcha_success->success==true) {
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
    header('Location: thanks.html');
    exit;
  }
} else {
 die("Direct access not allowed!");
}
?>

This works great but can it be any better?

1 Like

I believe I have this working the wait I want now. Please see this post for a complete tutorial: How to use PHP mail() and ReCaptcha with Exported Site Forms.