PHP: Random "1" outputted to the screen - php

I have the following code:
if ($currentStage == 7)
{
echo include("include/contentP7.php");
}
The content of "content7.php" exists however it is blank.
But when $currentStage is equal to 7 the page is displayed and a random "1" is outputted although "content7.php" is blank.
I assume it may be to do with returning "True" to the if statement. Why is this and how can I remove this "1".

include returns TRUE upon success, when echoed, it becomes 1.
Omit the echo statement:
if ($currentStage == 7) {
include("include/contentP7.php");
}
Include should be on its own.

include probably returns true(1) when includei successful. Remove the echo to get rid of the 1

if ($currentStage == 7)
{
include("include/contentP7.php");
}
I don't understand what the other parts were intended to do. If you wanted to echo a value from contentP7, place that content into a variable (perhaps a HEREDOC or something). Then include and echo like this:
if ($currentStage == 7)
{
include("include/contentP7.php");
echo $contentP7_variable;
}
The "1" or True value might be returned because you are echoing the returned status of the include() but I am not sure how since php.net's manual explains that it is a language construct. I can't test this right now, unfortunately.

Related

if statement in php not respecting false case

PHP is still new to me so excuse me if I am missing something basic here.
I have some very simple code:
echo $_GET['initState'];
if ($_GET['initState']) {
$num = 10;
}
else {
$num = PHP_INT_MAX;
}
echo $num;
And when I check my logs, I see the following: false10
So initState is false, and yet num is assigned to 10
But when I change the code to the following:
echo $_GET['initState'];
if ($_GET['initState'] == 1) {
$num = 10;
}
else {
$num = PHP_INT_MAX;
}
echo $num;
My output is now working correctly: false9223372036854775807
What am I missing here?
Here is the #GET code:
#GET("getreleases.php")
Call<ReleaseModelResponse> getReleases(#Query("initState") boolean initState);
Appreciate any insight that can be provided here.
EDIT Actually, maybe my code is not working correctly in either case, which is why I have been looking closely at this problem for a while now. I noticed my activity was always loading more than 10 items so this must mean neither versions of the code work correctly for me.
Just to be sure, I checked my logs again when performing an action that results in initState being true, and this is what I see: true9223372036854775807
In the first version of your code, the if statement is checking if the value of $_GET['initState'] is "truthy". In PHP, any non-empty string, non-zero number, or non-null value is considered "truthy". So even though the value of $_GET['initState'] is "false", it is still considered "truthy" in the if statement; therefore $num is assigned the value of 10.
In the second version of your code, you are explicitly checking if the value of $_GET['initState'] is equal to 1. Since it is not equal to 1, the else block is executed and $num is assigned the value of PHP_INT_MAX.
It seems that you are using this code in a REST API and sending a boolean value in the query parameter, but in PHP, booleans are not directly passed in query parameters, instead they are passed as strings "true" or "false", so in the first version of your code, the value of $_GET['initState'] is "false" string and its considered truthy, but in the second version, the value of $_GET['initState'] is "false" string and you are comparing it with 1, which is not equal and it's not truthy.
You could try to change the if($_GET['initState'] == 1) to if($_GET['initState'] === "true") or if($_GET['initState'] == true), this will check for the boolean value and not the string.

Why won't PHP print 0 value?

I have been making a Fahrenheit to Celsius (and vise versa) calculator. All of it works just great, however when I try to calculate 32 fahrenheit to celsius it's supposed to be 0, but instead displays nothing. I do not understand why it will not echo 0 values.
Here is some code:
<?php
// Celsius and Fahrenheit Converter
// Programmed by Clyde Cammarata
$error = '<font color="red">Error.</font>';
function tempconvert($temptype, $givenvalue){
if ($temptype == 'fahrenheit') {
$celsius = 5/9*($givenvalue-32);
echo $celsius;
}
elseif ($temptype == 'celsius') {
$fahrenheit = $givenvalue*9/5+32;
echo $fahrenheit;
}
else {
die($error);
exit();
}
}
tempconvert('fahrenheit', '50');
?>
looks like $celcius has value 0 (int type) not "0" (string type), so it wont echoed because php read that as false (0 = false, 1 = true).
try change your code
echo $celcius;
to
echo $celcius."";
or
echo (string) $celcius;
it will convert your variable to string
when it printed nothing, could you have had a typo in the temptype 'fahrenheit'?
The code matches temptype, and if it's not F or C it errors out. Except that $error is not declared global $error; which uses a local undefined variable (you must not have notices enabled which would warn you), and undefined prints as the "" empty string.
die() is equivalent to exit(). Either function with the single parameter as an integer value of 0 indicates to PHP that whatever operation you just did was successful. For your function, if you want the value 0 output, you would want to use echo or print, not die() or exit().
Further, consider updating your function to return the value instead of directly outputting it. It will make your code more reusable.
More info about status codes here:
http://php.net/manual/en/function.exit.php
echo (float) $celcius;
This will do the work for you.

PHP Multiple condition if statement returning nothing

I have been trying to figure this out for weeks, it is a simple statement yet it never executes the if statement. I'm echoing the variables to the screen so I know they exist and each condition is true, but the echo "something" never executes.
if ($db_a==$session_a && $db_b==$session_b && $dbfreq_b=="1")
{
echo "something";
}
I thought it was just the brackets as I had this originally:
if (($db_a==$session_a) && ($db_b==$session_b) && ($dbfreq_b=="1"))
I am comparing variables stored in a MYSQL database with session variables.
If I use Var_dump the db variables are null, yet they echo the expected string value to the screen.
$db_a="username";
$session_a="username";
$db_b=="keyword string"; -mostly one word but could be multiple
$session_b=="keyword string";
$dbfreq_b="1"; - This is the frequency that the keyword appears in the MYSQL database
using vardump $db_a and $db_b are NULL yet they echo what I am expecting to see to the browser.
Hopefully this explains things a bit more?
Thank you for the very prompt help!!
If as you say $db_a = $session_a AND $db_b = $session_b AND $dbfreq_b = 1 then it's impossible that condition returns false.
Please check your code again (all 5 variables) and make sure ALL of the conditions are met.
You could just split your single IF into three separate conditions so that you know which one returns false.
if ($db_a == $session_a) {
echo "first OK\n;"
}
if ($db_b == $session_b) {
echo "second OK\n";
}
if ($dbfreq_b == "1") {
echo "third OK";
}
Could you add the values of your variables to your question?

How do I write this PHP string that has an equal sign within it?

<?
$xm="1?x=1";
if($_GET["x"]=="1" || $_GET["x"]=='$xm'){ ?>
String Works
<? } ?>
Basically the URL reads:
http://site.com/shop/category/product?x=1?x=1
This happens when a form is submitted. I do not have access to change it to:
http://site.com/shop/category/product?x=1&x2=1
Change it to:
<?
$xm="1?x=1";
if($_GET["x"]=="1" || $_GET["x"]=="{$xm}"){ ?>
String Works
<? } ?>
If the URL looks like ...product?x=1?x=1, the $_GET array will look like this:
array(1) {
["x"] => string(5) "1?x=1"
}
So your condition just needs to look like:
if ($_GET["x"] == '1?x=1')
Your problem is simply that you quote the variable $xm in single quotes, which literally results in the string "$xm".
Now obviously, that's a rather broken URL. If you don't know how many times ?x=1 will occur in it, it's hard to compare to anything constant.
What you have should work, with the change that '$xm' will not evaluate to "1?x=1":
if (isset($_GET['x']) && ($_GET['x'] == 1 || $_GET['x'] == $xm)) {
echo 'string works';
}
If the argument will always be numeric, you can also just write this to coerce $_GET['x'] into an integer before comparison:
if (isset($_GET['x']) && $_GET['x'] == 1) {
echo 'string works';
}
This works because '1?x=1' == 1, but also '1?x=2' == 1 ... if that's not the desired behavior, do let me know.
use http_build_query whenever you want to build links
equal sign has special meaning in url context. they need to be encoded to treat them like literal value either with urnencode() or rawurlencode() or base64 encode

Php test empty string

I have a bit of php code that I'm not understanding why it is acting as it is. I have a variable called contactId that I want to test to see if it is empty. However even if it is empty it evaluates to true. Code is below. Thanks in advance.
print "*".$contactId."*<br/>";
if($contactId != '')
{
//queryContact($contactId);
print "Contact Present<br/>";
}
result returned to screen is:
**
Contact Present
If you want to see exactly what your string is, simply use var_dump(), like this, for instance:
var_dump($contactId)
instead of
print "*".$contactId."*<br/>";
Couple of things you can try:
if (!empty($contactId)) {
// I have a contact Id
}
// Or
if (strlen($contactId) > 0) {
// I have a contact id
}
In my experience I have often used the latter of the two solutions because there have been instances where I would expect a variable to have the value of 0, which is valid in some contexts. For example, if I have a drink search site and want to indicate if an ingredient is non-alcoholic I would assign it a value of 0 (i.e. IngredientId = 7, Alcoholic = 0).
Do it with if (isset($contactId)) {}.
You likely want:
if (strlen($contactId))
You'll want to learn the difference between '' and null, and between == and ===. See here: http://php.net/manual/en/language.operators.comparison.php
and here: http://us3.php.net/manual/en/language.types.null.php
In future, use if(!empty($str)) { echo "string is not empty"}.

Categories