Reputation: 79
my index file is
<body>
<form method="POST" action="post.php" >
<input name="name">
<input type="submit" value="submit">
</form>
</body>
and post.php is
<?php
$sec = 'qaswed';
if($sec == $_POST['name'])
{
echo "true";
}
else
{
echo "false";
}
?>
When I am simply writing the TRUE in place of $_POST['name'] in post.php file then irrespective of what i submit in index file,the result is true as obvious i.e
if($sec == TRUE) { echo "true"; } else { echo "false"; }//true
But, When in index file if i send TRUE in the name parameter then why the output is coming false .. i.e
if($sec == $_POST['name']) { echo "true"; } else { echo "false"; }// false when name=TRUE
when I send this from other page variable (request) then it evaluates to false.why it happens?
Upvotes: 2
Views: 67
Reputation: 10572
In first comparison value of string 'qaswed' automatically is casted to the boolean value in order to comapre to the bool. When you compare different data types one of it is casted to another type.
If you want to compare also types of the variables you should use Identical Comparison Operator.
var_dump('qaswed'); // string(6) "qaswed"
var_dump((bool)'qaswed'); // bool(true)
var_dump('qaswed' == true); // bool(true)
var_dump('qaswed' === true); // bool(false)
In second case you compare string types.
var_dump('TRUE'); // string(4) "TRUE"
var_dump('qaswed'); // string(6) "qaswed"
var_dump('qaswed' == 'TRUE'); // bool(false)
var_dump('qaswed' === 'TRUE'); // bool(false)
Upvotes: 1
Reputation: 9
i just added "if (isset($_POST['name']))" for checking the name is set or not
//post.php
<?php
if (isset($_POST['name']))
{
$sec = 'qaswed';
if ($sec == $_POST['name'])
{
echo "true";
}
else
{
echo "false";
}
}
?>
Upvotes: 0
Reputation: 883
When you write if ($sec == TRUE)
, then it's true
, because you are using automatic type conversion with the ==
operator, and php converts the $sec
string to bool type, where since it's not (bool)false
(not string 'false'!!!!) or (int)0
, it becomes true, and the true === true = true
.
If you don't want the php to automatically convert the values in the if, then use ===
instead of ==
, which will also check the type.
In the other case you are sending a "true" string and you have "qaswed" string which is obviously not the same, and since both of them are strings there are no type conversion like in the previous case.
Upvotes: 4