PHP Check domain of email being registered is a 'school.edu' address

后端 未结 7 1132
心在旅途
心在旅途 2020-12-10 02:59

I need to write a function for a project i\'m working on for fun, where we\'re making a site only accessible to students, staff, and alumni at an institution.

Let\'s

7条回答
  •  -上瘾入骨i
    2020-12-10 03:24

    There's a few ways to accomplish this, here's one:

    // Make sure we have input
    // Remove extra white space if we do
    $email = isset($_POST['email']) ? trim($_POST['email']) : null;
    
    // List of allowed domains
    $allowed = [
        'school.edu',
        'school2.edu',
        'school3.edu'
    ];
    
    // Make sure the address is valid
    if (filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        // Separate string by @ characters (there should be only one)
        $parts = explode('@', $email);
    
        // Remove and return the last part, which should be the domain
        $domain = array_pop($parts);
    
        // Check if the domain is in our list
        if ( ! in_array($domain, $allowed))
        {
            // Not allowed
        }
    }
    

提交回复
热议问题