Reputation: 85
Im currently trying to figure out how can you check and see if a $_POST['email'] contains a specific string using php.
I currently tried
}elseif(empty($_POST['email']) || !strpos('@gmail.com', $_POST['email'])) {
the output says that the strpos does not contain the ending, when it does. What am i currently doing wrong, or is there another way of doing this?
I only want people to be able to register with gmail, and not any other unknown email accounts for spam use.
Upvotes: 2
Views: 5869
Reputation: 74217
You're probably best off using preg_match
with the \b
pattern match instead of strpos
. Plus, strpos
will match GMAIL
should you not want uppercase letters, you would want to use stripos
instead, that will match it as case-insensitive, an FYI.
Using strpos
will match gmail.comm
instead of the intended gmail.com
, which I'm sure you don't want. Users could very well enter [email protected]
and still be considered valid, something else I'm sure you don't want, which will fail in either trying to mail back, or using an auto-responder.
"The \b in the pattern indicates a word boundary, so only the distinct * word "web" is matched, and not a word partial like "webbing" or "cobweb"
This will not match @GMAIL.com or @GMAIL.comm but will match @gmail.com but not @gmail.comm
<?php
if(isset($_POST['submit'])) {
$contains = "@gmail.com";
$email = $_POST['email'];
// or use (as outlined below)
// if(isset($_POST['email']) && preg_match("/\b(@gmail.com)\b/", $_POST['email']))
if(isset($_POST['email']) && preg_match("/\b($contains)\b/",$email )) {
echo 'yey! gmail!';
} else {
echo 'invalid input!';
}
}
?>
<form method="POST">
<input type="text" name="email" />
<input type="submit" name="submit" />
</form>
You can also just do the following, replacing what you're presently using:
if(isset($_POST['email']) && preg_match("/\b(@gmail.com)\b/", $_POST['email']))
Upvotes: 1
Reputation: 1339
If you would like to try something else, instead of strpos
, you can do this:
if (empty($_POST['email'] || array_pop(explode('@', $email)) != "gmail.com") {
// Do something if the email is empty or the domain is not "gmail.com"
}
Upvotes: 1