This question already has answers here:
How to validate an email address in PHP
(15 answers)
Closed 2 years ago.
I have a PHP script that runs when a form button is clicked. Everything is working fine, apart from a routine that checks for email format. I have tried using the inbuilt PHP filter function for that but it doesnt even seem to run (I am using a suitable version of PHP for this). I am checking for the existence of the 'at' symbol and a dot for the domain name, just on the dev machine WAMP webserver at the moment. If I enter an invalid address (say abc123 - i.e., no 'at' symbol, no dot) it seems to think everything is OK and loads the appropriate page. Code here: (tempvar echoes correctly by the way, and is just there for experiment)
$_SESSION['emailaddress']=$_POST['unamebox'];
$tempvar = $_SESSION['emailaddress'];
function checkEmail($tempvar) {
$find1 = strpos($tempvar, '#');
$find2 = strpos($tempvar, '.');
return ($find1 !== false && $find2 !== false && $find2 > $find1);
}
if ( checkEmail($tempvar) )
{
echo "OK";
}
else
{
echo "Bad email format!";
}
Because strpos return an integer if found the template in string otherwise return false. Now the !== operator is also match variable types!
When find1 or find2 strpos is match, the !== return false value!
Related
This question already has answers here:
Email validation using regular expression in PHP
(11 answers)
Closed 3 years ago.
Everybody, I need To allow just string and numbers and dots "." in my email
'email' => 'required|string|email|unique:users|not_regex:/^.+$/i|regex :/^.+#.+$/i',
My Code Here is not allowing for "." i ned to allow just "." and block others like
[# / \ $%^&* etc]
You actually don't need a regex nowadays to validate a string consisting of an email address that should only include letters, numbers, and the # and dot symbols. PHP allows for proper validation when you apply filter_var() twice, first to sanitize the data and then again to validate it, as follows:
<?php
// Variables to check
$emailA = "john1.doe#example.com";
$emailB = "john1.doe#example#.com";
// Remove all illegal characters from email
$emailValid = filter_var($emailA, FILTER_SANITIZE_EMAIL);
$emailInvalid = filter_var($emailB, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (filter_var($emailValid, FILTER_VALIDATE_EMAIL)) {
echo("$emailValid is a valid email address"),"\n";
} else {
echo("$emailValid is not a valid email address");
}
if (filter_var($emailInvalid, FILTER_VALIDATE_EMAIL)) {
echo("$emailInvalid is a valid email address");
} else {
echo("$emailInvalid is not a valid email address");
}
See live code
Note, if this code seems familiar, I admit that I modified the example given here :)
However if you insist on using a regex, here is one way to do so:
<?php
$emailA = "john1#here.com";
$emailB = "john1#here#.com";
function validateEmail( $email ){
$regex = "/^[a-zA-Z0-9.]+#[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}/";
$error = "\nOnly letters, numbers, dot and # are allowed";
echo (preg_match($regex,$email))? "$email is valid\n" : "$error - $email is invalid\n";
return true;
}
validateEmail( $emailA );
validateEmail( $emailB );
See live code
It might seem kind of odd to have validateEmail() return true whether an email is valid or invalid. The return value can be useful if you need to verify that this function actually executed; see example here.
I have this function in a class:
protected $supportedWebsitesUrls = ['www.youtube.com', 'www.vimeo.com', 'www.dailymotion.com'];
protected function isValid($videoUrl)
{
$urlDetails = parse_url($videoUrl);
if (in_array($urlDetails['host'], $this->supportedWebsitesUrls))
{
return true;
} else {
throw new \Exception('This website is not supported yet!');
return false;
}
}
It basically extracts the host name from any random url and then checks if it is in the $supportedWebsitesUrls array to ensure that it is from a supported website. But if I add say: dailymotion.com instead of www.dailymotion.com it won't detect that url. Also if I try to do WWW.DAILYMOTION.COM it still won't work. What can be done? Please help me.
You can use preg_grep function for this. preg_grep supports regex matches against a given array.
Sample use:
$supportedWebsitesUrls = array('www.dailymotion.com', 'www.youtube.com', 'www.vimeo.com');
$s = 'DAILYMOTION.COM';
if ( empty(preg_grep('/' . preg_quote($s, '/') . '/i', $supportedWebsitesUrls)) )
echo 'This website is not supported yet!\n';
else
echo "found a match\n";
Output:
found a match
You can run a few checks on it;
For lower case vs upper case, the php function strtolower() will sort you out.
as for checking with the www. at the beginning vs without it, you can add an extra check to your if clause;
if (in_array($urlDetails['host'], $this->supportedWebsitesUrls) || in_array('www.'.$urlDetails['host'], $this->supportedWebsitesUrls))
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
I am starter php developer, I know, if else, or, elseif... but I don't understand those : ? and other symbols. So can you tell me what this lines mean:
$success = $success ? $b->save(false) : $success;
if (!success) // shouldn't this be without "!"
$transaction->commit(); // this means "do the job, if ok"
else
$transaction->rollBack(); // this means "don't do the job, if not ok"
Also, can you tell me how to call this symbols, I don't know their name and so I can't find tutorials about them
It's pretty common in a lot of languages, you can find this Ternary Operations for example in javascript aswell
It is a short hand for an if/else.
The part before the ? is the condition, the next part is the code to execute if the condition returns true, and the last part (after the :) if it returns false:
condition ? if true : if false;
$a = 3 > 5 ? 'three is greater than five' : 'three is lesser than five';
In this case $a would be three is lesser than five;
I would recommend ternary operations only for very simple conditions/results, if not, you end up writting less maintainable code, sacrificing shortness for legibility
the above code looks like if $success from previous transactions was true , try $b->save(false) and then put the returned value from $b->save(false) into $success.
$b->save(false) means save without validation, and after successful save, will return true
then the if part is very clear
That's a Ternary Operator, a short form for an if statement.
$success = $success ? $b->save(false) : $success;
is the same as
if($success) {
$success = $b->save(false);
} else {
$success = $success;
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Users to register only lower case letters
Hi, I have this register page , and i would like to have the script register only lower case letters : pretty
I do not want it to register :Pretty , PRETTy , PRETTY ... Here is the code , what do i need to add to it ?
public function addField($field_name){
if (!array_key_exists($field_name, $this->fields))
{
if ($field_name=='username') {
$field = new field_join_username();
parent::registerField($field);
}
if ($field_name=='email') {
$field = new field_join_email();
parent::registerField($field);
}
}
parent::addField($field_name);
}
Where's that code taken from? Are you trying to change existing code?
As far as I can see, this only adds fields not values of fields where the strtolower should be applied, so applying strtolower to field_name won't do the trick ... but it's hard to guess where to place strtolower without seeing the correct code snippet.
I am trying to create a script that will only execute its actions if the email address the user enters is from a specific domain. I created a regex that seems to work when testing it via regex utility, but when its used in my PHP script, it tells me that valid emails are invalid. In this case, I want any email that is from #secondgearsoftware.com, #secondgearllc.com or asia.secondgearsoftware.com to echo success and all others to be rejected.
$pattern = '/\b[A-Z0-9\._%+-]+#((secondgearsoftware|secondgearllc|euro\.secondgearsoftware|asia\.secondgearsoftware)+\.)+com/';
$email = urldecode($_POST['email']);
if (preg_match($pattern, $email))
{
echo 'success';
}
else
{
echo 'opposite success';
}
I am not really sure what's futzed with the pattern. Any help would be appreciated.
Your regular expression is a bit off (it will allow foo#secondgearsoftwaresecondgearsoftware.com) and can be simplified:
$pattern = '/#((euro\.|asia\.)?secondgearsoftware|secondgearllc)\.com$/i';
I've made it case-insensitive and anchored it to the end of the string.
There doesn't seem to be a need to check what's before the "#" - you should have a proper validation routine for that if necessary, but it seems you just want to check if the email address belongs to one of these domains.
You probably need to use /\b[A-Z0-9\._%+-]+#((euro\.|asia\.)secondgearsoftware|secondgearllc)\.com/i (note the i at the end) in order to make the regex case-insensitive. I also dropped the +s as they allow for infinite repetition which doesn't make sense in this case.
Here's an easy to maintain solution using regular expressions
$domains = array(
'secondgearsoftware',
'secondgearllc',
'euro\.secondgearsoftware',
'asia\.secondgearsoftware'
);
preg_match("`#(" .implode("|", $domains). ")\.com$`i", $userProvidedEmail);
Here's a couple of tests:
$tests = array(
'bob#secondgearsoftware.com',
'bob#secondgearllc.com',
'bob#Xsecondgearllc.com',
'bob#secondgearllc.net',
'bob#euro.secondgearsoftware.org',
'bob#euro.secondgearsoftware.com',
'bob#euroxsecondgearsoftware.com',
'bob#asia.secondgearsoftware.com'
);
foreach ( $tests as $test ) {
echo preg_match("`#(" .implode("|", $domains). ")\.com$`i", $test),
" <- $test\n";
}
Result (1 is passing of course)
1 <- bob#secondgearsoftware.com
1 <- bob#secondgearllc.com
0 <- bob#Xsecondgearllc.com
0 <- bob#secondgearllc.net
0 <- bob#euro.secondgearsoftware.org
1 <- bob#euro.secondgearsoftware.com
0 <- bob#euroxsecondgearsoftware.com
1 <- bob#asia.secondgearsoftware.com
I suggest you drop the regex and simply use stristr to check if it matches. Something like this should work:
<?php
// Fill out as needed
$domains = array('secondgearsoftware.com', 'secondgearllc.com');
$email = urldecode($_POST['email']);
$found = false;
for(i=0;i<count($domains);i++)
{
if ($domains[i] == stristr($email, $domains[i]))
$found = true;
}
if ($found) ...
?>
The function stristr returns the e-mail address from the part where it found a match to the end, which should be the same as the match in this case. Technically there could be something prior to the domains (fkdskjfsdksfks.secondgeartsoftware.com), but you can just insert "#domainneeded.com" to prevent this. This code is also slightly longer, but easily extended with new domains without worrying about regex.