You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP服务端限制仅处理@gmail.com后缀的邮箱地址

Restrict Email Processing to Only Gmail Addresses in PHP

Hey there! Since you want to enforce the Gmail-only restriction on the backend (way more reliable than just frontend validation), let's tweak your PHP code step by step.

Here's the modified code with domain validation added:

<?php
set_time_limit(0);

if(isset($_POST['email'])) {
    $mail = explode('@', $_POST['email']);
    
    // First, validate we have a valid email structure and it's Gmail
    if(count($mail) !== 2 || strtolower(trim($mail[1])) !== 'gmail.com') {
        echo '<div class="box"><div class="title">Error</div><p>Please enter a valid Gmail address (ending with @gmail.com).</p></div>';
        exit; // Stop further execution if not a Gmail address
    }

    $email = $mail[0];
    $domain = '@'.$mail[1];
    
    // Your existing sanitization steps (simplified)
    $email = trim($email);
    $domain = trim($domain);
    $email = stripslashes($email);
    $domain = stripslashes($domain);
    $email = htmlentities($email);
    $domain = htmlentities($domain);
    
    $res = addDOT($email);
    echo '<div class="box"><div class="title">Total: '.sizeof($res).'</div><textarea type="text">';
    foreach($res as $mcMails) {
        echo nl2br($mcMails.$domain).PHP_EOL;
    }
    echo '</textarea></div>';
}

function addDOT($str){
    if(strlen($str) > 1) {
        $ca = preg_split("//",$str);
        array_shift($ca);
        array_pop($ca);
        $head = array_shift($ca);
        $res = addDOT(join('',$ca));
        $result = array();
        foreach($res as $val) {
            $result[] = $head . $val;
            $result[] = $head . '.' .$val;
        }
        return $result;
    }
    return array($str);
}
?>

Key changes explained:

  • Domain Validation Check: Right after splitting the email, we verify two critical things:
    1. The email is split into exactly two parts (ensuring it has a single, valid @ symbol)
    2. The domain part — after trimming whitespace and converting to lowercase — is exactly gmail.com. This handles edge cases like GMAIL.COM or gmail.com (with trailing spaces)
  • Error Handling: If validation fails, we show a user-friendly error message and stop the script immediately so no invalid addresses get processed.
  • Cleaner Sanitization: I combined your separate ltrim and rtrim calls into a single trim() function (it does the same work but makes the code neater).

This way, even if someone bypasses your frontend validation (which is trivial to do), your backend will block any non-Gmail addresses from being processed.

内容的提问来源于stack exchange,提问作者NotoriusSha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:22:49