PHP Statement always return false - php

I have a little script witch fetches data from IMDB with omdbapi.
I've managed to get the data from the site, but when I try to check if the movie's poster is valid, it always returns false.
if(!$info['Poster'] == "N/A") {
$url = $info['Poster'];
$img = 'images/'.$info["imdbID"].'.jpg';
file_put_contents($img, file_get_contents($url));
echo 'Downloaded';
} else {
echo '!Downloaded';
$noCover = true;
}
The $info['Poster'] is containing data similar to this:
http://ia.media-imdb.com/images/M/MV5BMTM0MDgwNjMyMl5BMl5BanBnXkFtZTcwNTg3NzAzMw##._V1_SX300.jpg
It was working a while ago, but it somehow stopped...

Your if statement is written incorrectly. !$info['Poster'] means if $info['Poster'] is not true. If there is a value it will be translated to false as PHP's type juggling converts any non-empty string to true and the ! operator makes that false. false does not equal N/A as type juggling converts that to true (non-empty strings are always true). false is not equal to `true.
You mean to use != which means not equal to
if($info['Poster'] != "N/A") {

Just move the ! from your condition, And it should work as expected. You are asking in your condition if $info['Poster'] is false, and it wont be false because it will have a string value. So, you are comparing a boolean value with a string value, false will be always different to "N/A:
if($info['Poster'] !== "N/A") {
$url = $info['Poster'];
$img = 'images/'.$info["imdbID"].'.jpg';
file_put_contents($img, file_get_contents($url));
echo 'Downloaded';
} else {
echo '!Downloaded';
$noCover = true;
}

Related

How to treat zero values as true using php?

Here is my sample code:
$issue_id = $_POST['issue_id'];
if(!empty($issue_id)){
echo 'true';
}
else{
echo 'false';
}
If I pass 0 to $_POST['issue_id'] by form submitting then it echo false. Which I want is: Condition will be true if the following conditions are fulfilled:
1. true when I pass any value having 0.
2. false when I don't pass any value. i.e: $_POST['issue_id'] is undefined.
I also tried this:
if(!isset($issue_id)){
echo 'true';
}
else{
echo 'false';
}
if(!empty($issue_id) || $issue==0){
echo 'true';
}
else{
echo 'false';
}
The last one is okay, meaning if I pass any value having ZERO then it will echo true. But it will also echo true if I don't pass any value. Any idea?
The last is okay, meaning if I pass any value having ZERO then it echo true. But it also echo true if I don't pass any value. Any idea?
if (isset($_POST["issue_id"]) && $_POST["issue_id"] !== "") {
}
please notice I used !== not !=. this is why:
0 == "" // true
0 === "" // false
See more at http://php.net/manual/en/language.operators.comparison.php
also if you are expecting number you can use
if (isset($_POST["issue_id"]) && is_numeric($_POST["issue_id"])) {
}
since is_numeric("") returns false
http://php.net/manual/en/function.is-numeric.php
Alternatively if you expect number good option is filter_var
if (isset($_POST["issue_id"]) {
$issue_id = filter_var($_POST["issue_id"], FILTER_VALIDATE_INT);
if ($issue_id !== false) {
}
}
since filter_var("", FILTER_VALIDATE_INT) will returns false and filter_var("0", FILTER_VALIDATE_INT) will return (int) 0
http://php.net/manual/en/function.filter-var.php
if(isset($_POST['issue_id'])) {
if($_POST['issue_id'] == 0) {
echo "true";
}
else {
echo "false";
}
}
When you get data from a form, remember:
All text boxes, whether input or textarea will come as strings. That includes empty text boxes, and text boxes which contain numbers.
All selected buttons will have a value, but buttons which are not selected will not be present at all. This includes radio buttons, check boxes and actual buttons.
This means that $_POST['issue_id'] will be the string '0', which is actually truthy.
If you need it to be an integer, use something like: $issue_id=intval($_POST['issue_id']);
#Abdus Sattar Bhuiyan you can also full fill your two condition like below one:
<?php
$_POST["issue_id"] = "0";
$issue_id = isset($_POST['issue_id']) ? (!empty($_POST['issue_id']) || $_POST['issue_id'] === 0 || $_POST['issue_id'] === "0") ? true : false : false;
if($issue_id){
echo 'true';
}
else{
echo 'false';
}

How to check the value and type of a unknown var

I have a variable that can be int or bool, this is because the db from where im querying it change the variable type at some point from bool to int, where now 1 is true and 0 is false.
Since php is "delicate" with the '===' i like to ask if this is the correct why to know if that var is true:
if($wallet->locked === 1 || $wallet->locked === true)
I think in this way im asking for: is the type is int and one? or is the var type bool and true?
How will you approach this problem?
Your code is the correct way.
It indeed checks if the type is integer and the value is 1, or the type is boolean and the value is true.
The expression ($x === 1 || $x === true) will be false in every other case.
If you know your variable is an integer or boolean already, and you're okay with all integers other than 0 evaluating to true, then you can just use:
if($wallet->locked) {
Which will be true whenever the above expression is, but also for values like -1, 2, 1000 or any other non-zero integer.
$wallet->locked = 1;
if($wallet->locked === true){
echo 'true';
}else{
echo 'false';
}
will produce:
false
and
$wallet->locked = 1;
if($wallet->locked == true){
echo 'true';
}else{
echo 'false';
}
will produce:
true
Let me know if that helps!
Your solution seems to be perfect, but You can also use gettype. After that You can check the return value with "integer" or "boolean". Depending on the result You can process the data the way You need it.
solution #1. If $wallet has the value of either false or 0, then PHP will not bother to check its type (because && operator is short-circuit in PHP):
$wallet = true;
//$wallet = 1;
if( $wallet && (gettype($wallet) == "integer" || gettype($wallet) == "boolean") )
{ echo "This value is either 'true and 1' OR it is '1 and an integer'"; }
else { echo "This value is not true"; }
solution #2 (depending on what You want to achieve):
$wallet = 0;
//$wallet = 1; // $wallet = 25;
//$wallet = true;
//$wallet = false;
if($wallet)
{ echo "This value is true"; }
else { echo "This value is not true"; }

Boolean input flipping

I'm getting really strange results on a php script that takes boolean input. The idea is that the data needs to be stored as either a 1 or a 0, but the input to the php script is a string in true/false format. Check this out:
<?php
function boolToBinary($str) {
echo $_POST['wants_sms'] . " " . $str;
die();
// posting this so that you can see what this function is supposed to do
// once it is debugged
if ($str == true) {
return 1;
} else {
return 0;
}
}
$gets_sms = boolToBinary($_POST['wants_sms']);
Here is the output from this function:
false true
How can that be??? Thanks for any advice.
EDIT: Solution: Still not sure why my output was flipped, but the fundamental problem is solved like this:
if ($str === 'true') {
return 1;
} else {
return 0;
}
Thanks to RocketHazmat for this.
http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
see this example:
var_dump((bool) "false"); // bool(true)
And the explanations:
When converting to boolean, the following values are considered FALSE:
...
the empty string, and the string "0"
...
Every other value is considered TRUE (including any resource).
In your case the $_POST['wants_sms'] variable contains a string "false";

If $_POST is empty Multiple function

I have the following $_POST function to check if the fields of 'start', 'middle' and 'end' is empty or not.
if(!empty($_POST['start'])) {
$description = "a sentence".$_POST['start']." with something in the START.";
}
if(!empty($_POST['middle'])) {
$description = "a sentence".$_POST['middle']." with something in the MIDDLE.";
}
if(!empty($_POST['end'])) {
$description .= "a sentence".$_POST['end']." with something in the END.";
}
I want to check the values in one function, in other words I want to check multiple values at the same time. I have seen few method but not sure which one is right, using comma or && or ||, something like below ...
if(!empty($_POST['start']) , (!empty($_POST['middle']) , (!empty($_POST['end']))
or
if(!empty($_POST['start']) && (!empty($_POST['middle']) && (!empty($_POST['end']))
or
if(!empty($_POST['start']) || (!empty($_POST['middle']) || (!empty($_POST['end']))
Can anyone tell me the right code for this kind of formation?
here are some basic.. i made it as a comment(as i was not sure if this is the thing you asked for) but i guess an answer would be appropriate with a bit of details.
the AND operatior
the && will check every condition and if all are true it will return true...
take it like this
if(FALSE && TRUE)
it will always return False and if will not execute because one of the condition is false
The OR operator
THe || will check the first condition if its true it will return true else check the second condition If all are false(not even a single is true) it will return false.
again following the previous example
if(TRUE || False || False)
now the compiler checks the first condition if its true it will ignore the next two conditions and return true.
if(FALSE || FALSE || FALSE) - this will return false as all are false
THe comma Operator
if you , operatior then the last condition to the right will be evaluated and if it is true then it will return true else false
example
if(True,True,True,False) - it will return false
if(FALSE, TRUE, FALSE, TRUE) - it will return true
so choose the operator according to your logic.
USE THIS :
if((!empty($_POST['start'])) && (!empty($_POST['start'])) && (!empty($_POST['start'])));
Your looking for something like:
// Establish valid post key values
$valid_post_variables = array_flip( ['start', 'middle', 'end'] );
// Fetch post data
$post = $_POST;
// $result will contain the values of post where the keys matched valid
$result = array_intersect_key( $post, $valid_post_variables );
// if the resulting array contains our 3 options, its go time
if ( count( $result ) == 3 ) {
//start middle and end where all passed via POST
}
function insertPost($before, $offset, $after)
{
if(!empty($_POST[$offset])) {
return $before . $_POST[$offset] . $after;
}
return '';
}
$description = insertPost('a sentence', 'start', ' with something in the START.');

php "if" condition mystery

I am running into a funny problem with a mischievous "if" condition :
$condition1="53==56";
$condition2="53==57";
$condition3="53==58";
$condition=$condition1."||".$condition2."||".$condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Why does the if condition pass?
Why does php echo "blah"? What do I do to make php evaluate the "if" statement and print "foo"?
The problem here is that you're putting your expressions in strings!
Your $condition1, $condition2, and $condition3 variables contain strings, and not the result of an expression, and the same goes for your $condition variable which will be a string that looks like 53==56||53==57||53==58. When PHP evaluates a string it considers it true if it is not empty and not equal to 0, so your script will output blah.
To fix this you just need to take your expressions out of the strings. It should look like this:
$condition1 = 53 == 56; // false
$condition2 = 53 == 57; // false
$condition3 = 53 == 58; // false
$condition = $condition1 || $condition2 || $condition3; // false || false || false = false
if ($condition) {
echo 'blah';
} else {
echo 'foo'; // This will be output
}
You're evaluating strings as booleans; they'll aways be true (except the strings "" and "0". Get rid of almost all of the quotes in your program.
Those aren't conditions, they're strings.
$condition1=53==56;
$condition2=53==57;
$condition3=53==58;
$condition=$condition1 || $condition2 || $condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Because you're not checking those variables, it's saying if (String) will always return true. (unless "")
You should be doing:
if(53==56 || 53==57 || 53==58)
{
echo "blah";
}
else
{
echo "foo";
}
All $condition* variables will evaluate to true. This is how PHP sees it:
if("53==56" || "53==57" || "53==58")
What you want is this:
$condition1 = 53==56;
$condition2 = 53==57;
$condition3 = 53==58;
It's because you're evaluating a string, and strings other than empty strings evaluate to true.
You are concatting a string together, a non-empty string equals TRUE in php.
Because when the if passes, $condition is a string (a concatenation of) containing the text of your conditions. Try using if(eval($condition)).
String always evaluate to true if its not empty
And btw php make implicit conversion to boolean

Categories