PHP表单邮箱查重异常:含空格邮箱被误判为新邮箱的排查
Hey there! Let's figure out why your space-trimming fix isn't working. The issue here is that str_replace(' ', '', ...) only targets regular half-width spaces—but users might accidentally input other whitespace characters like full-width spaces (common in Chinese input scenarios), tabs, or even newlines. Those won't get caught by your current code, which is why a@a.com with a non-standard space is still slipping through as a "new" email.
Here's how to fix it properly:
- Remove all whitespace characters (not just regular spaces) using a regex that matches any whitespace. The
\spattern in regex covers spaces, tabs, newlines, and full-width spaces, making it far more thorough. - Keep the sanitization step before escaping the input for the database (you had the right idea here, just incomplete sanitization).
Here's your updated code:
if (isset($_POST['submit'])) { // First, strip ALL whitespace from the email input $clean_email = preg_replace('/\s+/', '', $_POST['email']); // Then escape for database safety $email = $connessione->real_escape_string($clean_email); // Run the duplicate check as before $controlla_pro = mysqli_query($connessione,"SELECT invite_email FROM invite WHERE invite_email='$email'"); $risultato_controllapro = mysqli_num_rows($controlla_pro); if($risultato_controllapro == 0) { /*CODE OK*/ } else { /*CODE NOT OK*/ } }
Since valid email addresses can't contain any spaces at all, stripping all whitespace is the safest approach. If you wanted to be extra strict, you could also add front-end validation (like a simple JavaScript check) to alert users if they try to enter spaces in the email field before submitting the form—this improves user experience and reduces unnecessary backend requests.
内容的提问来源于stack exchange,提问作者user14846903

