What are some common methods for validating email inputs in PHP forms?

Validating email inputs in PHP forms is crucial to ensure that the data entered by users is in the correct format. Common methods for validating email inputs include using PHP's built-in filter_var function with the FILTER_VALIDATE_EMAIL flag, using regular expressions to check for a valid email format, and checking the domain of the email address against a list of allowed domains.

$email = $_POST['email'];

// Method 1: Using filter_var function
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
}

// Method 2: Using regular expressions
if (!preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
    echo "Invalid email format";
}

// Method 3: Checking domain against a list of allowed domains
$allowed_domains = ['example.com', 'test.com'];
$email_domain = explode('@', $email)[1];
if (!in_array($email_domain, $allowed_domains)) {
    echo "Email domain not allowed";
}