troubleshooting Question

Can I secure my email form from attacks?

Avatar of nouse33
nouse33 asked on
PHP
5 Comments1 Solution214 ViewsLast Modified:
I have an email form for people to contact me and some has been messing around with it in what appears to be a malicious way.  The for is setup to send to my email address using the email address they enter as the From: and Return-Path: headers. for the second time this week I've gotten 5 or so emails all at once saying they're from a random made up email address at my domain.  The weird thing is, somehow he's been inserting a cc: address in some of them.

I'm looking for someone to do a sort of security audit on my code and let me know what I can do to harden it.  I realize I haven't forced them to enter a valid email address but I didn't think it was a big deal.

Here's the non-html-form part of the script:

if($_POST['submit']) {
      $valid = 1;
      $error = "";
         foreach($_POST  as  $key=>$val) {
            if (is_string($val)) $_POST[$key] = stripslashes($val);
      }
      $name = $_POST['name'];
      $email = $_POST['email'];
      $body = $_POST['body'];
      if(!$name) {
            $error .= "Please enter your name.<br />";
            $valid = 0;
      }

      if(!$body) {
            $error .= "Please enter a message.<br />";
            $valid = 0;
      }
      
      if($valid) {
            if(!$email) $email = "webmaster@mydomain.com";
            $subject = "Email from contact form on mydomain.com";
            $email_to = "webmaster@mydomain.com";
            $message = "Email from: $name ($email)\n\n";
            $message .= $body;
            $from = "From: $email\r\nReturn-Path: $email";
            $result = mail($email_to,$subject,$message,$from);
            if($result) {
                  $msg =  "<span class='contact_msg'>Thanks for contacting us!<span><br /><br />";
            }
            else $msg = "<span class='contact_msg'>Error sending mail.  Please contact <a href='mailto:webmaster@mydomain.com'>webmaster@mydomain.com</a><span>";
      
      }

}
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 5 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros