0

I have a form where I ask for information, but some (such as email) is not required. When the form for email is not empty, I'd like the email to be validated and sanitized. My current method only submits the data that is not empty. What's the most effective way to do the validation and sanitization?

Current method

   if (empty($_POST["S_Email"])) {
   $S_Email = "";
   } else {
   $S_Email = $_POST["S_Email"];
   }        
Hunter
  • 241
  • 2
  • 11

1 Answers1

1

You're looking for PHP Validate Filters:

if (empty($_POST["S_Email"])) {

    //No email address POSTed through
    $S_Email = "";

} else {
    //Email address POSTed
    $S_Email = $_POST["S_Email"];

    //Validate email
    if(!filter_var($S_Email, FILTER_VALIDATE_EMAIL) === false){
        //Email is valid
    } else {
        //Email is invalid
    }

}
Ben
  • 8,894
  • 7
  • 44
  • 80