This question already has answers here:
The 3 different equals
(5 answers)
Closed 7 years ago.
I'm trying to compare two strings (one from my database and another supplied by the user) and see if they match! The problem I'm having is that they don't seem to match - even though the strings seems to be exactly identical?
My PHP code is below:
public function Verify($pdo, $id, $token) {
$prepsql = $pdo->prepare("SELECT * FROM Profiles WHERE id = '$id' LIMIT 1");
$prepsql->execute();
$currentrow = $prepsql->fetch();
$current = preg_replace("/[^a-zA-Z0-9]+/", "", $currentrow["token"]);
echo '<p>'.var_dump($current).'</p>';
echo '<p>'.var_dump($token).'</p>';
$token = preg_replace("/[^a-zA-Z0-9]+/", "", $token);
if ($current == null || $current = "") {
return false;
} else {
if (strcmp($token, $current) == 0) {
return true;
} else {
return false;
}
}
}
And here is the webpage output:
string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p>string(244) "CAAW4HRuZBuB4BACA7GffOAwLHgmLgMMLGQxDAw8IJDCwahZAh0S4wZAcP8Q9DmMwsDpBq7jFcH1EzUIsZBbhKov12utoYFQns0HhgB5xKLeDqtZBRqavaNjNSn7KAcObZAEcavQCRbGlVKZBArfDEHskBSR8qAoU543DVTZCOyHm5oYNDVafwHl0bAkc4jyIhh2YHEPaNpWGC0FhezsSidOgLjnfFq8CeLVxHH0nUZBMLgAZDZD"
<p></p><p>Not authenticated</p>
Not authenticated just means that this function is returning false...
What on earth am I doing wrong? As per advice given on other similar Stack Overflow answers, I've used the regex function to basically only keep alphanumeric characters but that has made no difference? It isn't a trimming issue either as that didn't work!
Any help would be much appreciated!
Thanks!
Here is your problem:
if ($current == null || $current = "") {
// ^ now `$current` is "", an empty string
You assign a new value to $current, an empty string.
You probably want something like:
if ($current == null || $current == "") {
// ^^ now you are comparing
Related
This question already has answers here:
whats the difference in parentheses in IF statements?
(9 answers)
Closed 2 years ago.
I have this simple if statement but I do not get the results I expect. If all three vars match then I get not supported as expected. However I expect that as soon as I change one of the vars to a value that is not in the if statement, e.g. $Main = "SomethingElse", for the if statement to not match and therefor echo supported. However, supported is only returned if all three vars do not match the if statement.
Why does this happen?
$Main = "Main_Other";
$Backup = "Back_None";
$online = "no";
if ($online == "no" && $Main == "Main_Other" && $Backup == "Back_Other" || $Backup == "Back_None") {
echo "not support";
} else {
echo "supported";
}
In your example the if statement will always return true if the value of $backup is set to Back_None.
Try using below code. Here it will check $backup value first using || operator and then it will check the result with && operator
$Main = "Main_Other";
$Backup = "Back_None";
$online = "no";
if ($online == "no" && $Main == "Main_Other" && ($Backup == "Back_Other" || $Backup == "Back_None")) {
echo "not support";
} else {
echo "supported";
}
This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
why the IF(the lastest one with else if and else) is doing all the time only first condition and only the first part ($filtry_1value[$key] = 'min_cena'), even if the condition shouldnt be true. I have another solution (less dynamic), if I will not fix this one, but I would like to know, why it is not working... I think it will be a trivial thing, but I cannot see it.
PS: I am working with laravel.
$filtry_1value = ['stat', 'lokalita', 'patro', 'min_cena', 'max_cena', 'min_uzitna_plocha', 'max_uzitna_plocha'];
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] = 'min_cena' OR $filtry_1value[$key] = 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] = 'max_cena' OR $filtry_1value[$key] = 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
may be-
foreach ($filtry_1value as $key => $filtr_1value) {
$filtr_1value = \Request::has($filtr_1value) ? \Request::get($filtr_1value) : null;
if(!empty($filtr_1value)){
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'>=',$filtr_1value);
}
elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
$query->where(substr($filtry_1value[$key], 4),'<=',$filtr_1value);
}
else {
$query->where($filtry_1value[$key],'=', $filtr_1value);
}
}
}
You need to use the double equal sign for comparisons. == not a single =
Your if's should look like:-
if ($filtry_1value[$key] == 'min_cena' OR $filtry_1value[$key] == 'min_uzitna_plocha') {
// ...
} elseif ($filtry_1value[$key] == 'max_cena' OR $filtry_1value[$key] == 'max_uzitna_plocha') {
// ...
}
This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I have a few lines of code
$case=0;
file_put_contents("text.txt", $case, FILE_APPEND);
if ($case = 1)
{
$message['a']="co";
}
if ($case = 0)
{
$message['a']="to";
}
echo $message['a'];
It will echo "co". Why is this? The file_put contents puts "0". However the if statement thinks it is 1 for some reason...
You are doing wrong in if condition. You doing assign instead of comparison. So here is the solution.
$case=0;
file_put_contents("text.txt", $case, FILE_APPEND);
if ($case == 1)
{
$message['a']="co";
}
if ($case == 0)
{
$message['a']="to";
}
echo $message['a'];
you have to use the comparison operator "==" when comparing values: otherwise you are assigning values (in this case you were assigning $case to be 1 and then the message was "co".
$case=0;
file_put_contents("text.txt", $case, FILE_APPEND);
if ($case == 1)
{
$message['a']="co";
}
if ($case == 0)
{
$message['a']="to";
}
echo $message['a'];
This question already has answers here:
Why does PHP consider 0 to be equal to a string?
(9 answers)
Closed 7 years ago.
I have the following code:
<?php
$starting_id = 0;
$params = array ('val' => $starting_id);
echo parse_params ($params);
function parse_params ($params)
{
$query = ' WHERE ';
if ($params['val'] === NULL) {
$query .= ' IS NULL';
return $query;
}
if ($params['val'] == 'NOT NULL') {
$query .= ' IS NOT NULL';
return $query;
}
return $query.' = '.$params['val'];
}
When I run it, I expect to see this:
WHERE
instead, I get the following:
WHERE IS NOT NULL
Any ideas why?
According to the PHP type comparison tables,
$var = 0 ; // (int)
if you compare $var == "string",
it will return true, you need to type check for this
$var === "string"
check php type comparison
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {