如何在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:
- The email is split into exactly two parts (ensuring it has a single, valid
@symbol) - The domain part — after trimming whitespace and converting to lowercase — is exactly
gmail.com. This handles edge cases likeGMAIL.COMorgmail.com(with trailing spaces)
- The email is split into exactly two parts (ensuring it has a single, valid
- 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
ltrimandrtrimcalls into a singletrim()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
相关产品推荐
相关产品推荐

