Reputation: 1864
I want to check the security input of a form. People should answer the security question with the words "allow", "Allow" or 'ALLOW'. These 3 answers are all accepted.
I tried code below but it doesn't pass the if
loop if I type one of these 3 answers. What I am doing wrong?
if( ! isset($_POST['security']) || empty($_POST['security']) || $_POST['security'] != 'allow' || $_POST['security'] != 'Allow' || $_POST['security'] != 'ALLOW') {
$error .= "<p class=\"message-error\">" . $messages['security_invalid'] . "</p>";
}
Upvotes: 0
Views: 70
Reputation: 7485
$security = 'Allow';
var_dump($security != 'allow' || $security != 'Allow');
Output:
bool(true)
The first comparison $security != 'allow'
evaluates to true above, which short-circuits the expression.
You could rewrite your expression to something like:
$security = 'Allow';
var_dump($security != 'allow' && $security != 'Allow' && $security != 'ALLOW');
Output:
bool(false)
Which is still a little unwieldy.
You'll likely need to check for errors in more than one place eventually. Splitting out your validation may help clear things up.
<?php
$security = isset($_POST['security']) ? $_POST['security'] : null;
$email = isset($_POST['email']) ? $_POST['email'] : null;
$errors = [];
if(!in_array($security, array('allow', 'Allow', 'ALLOW')))
$errors['security'] = 'Invalid security answer.';
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false)
$errors['email'] = 'Invalid email address.';
$has_errors = (bool) count($errors);
$error = '';
foreach($errors as $error)
$error .= "<p class=\"message-error\">" . $error . "</p>";
Upvotes: 0
Reputation: 3495
The problem basically comes when you try to compare string values. That's because you need to test it separetely like the following:
if (!isset($_POST['security']) || empty($_POST['security']) || ($_POST['security'] != 'allow' && $_POST['security'] != 'Allow' && $_POST['security'] != 'ALLOW'))
In fact the string value can be one of those strings and, of course, if for example is allow
then $_POST['security'] != 'Allow'
will fail.
Upvotes: 1
Reputation: 4104
Try this:
if( empty($_POST['security']) or strtolower($_POST['security']) != 'allow') {
$error .= "yaddayadaa";
}
Using empty()
is good enough for checking if its not set, or empty, or zero, or null. Then, just lowercase the post and check once for not being allow
.
Upvotes: 3