PHP multiplication weird behavior - php

I don't know if I have suffered some brain or sight damage, but I can't understand behavior of this code:
$po=1;
$po2=0;
echo $po.'*'.$po2.'=';
if($po*$po2) $po=1;
echo $po;
I'd expect the output to be 1*0=0, but actually it's 1*0=1.

$po is always 1. You initialize it to 1, and later in your if case, you have no else. So it remains 1.
Instead, add an `else:
$po = 1;
$po2 = 0;
echo $po.'*'.$po2.'=';
if ($po * $po2) {
// Unnecessary - it's already 1
$po = 1;
}
// Set it to 0...
else {
$po = 0;
}
echo $po;

Related

Header may not contain more than a single header, new line detected error [duplicate]

This question already has answers here:
getting warning "Header may not contain more than a single header, new line detected"
(9 answers)
Closed 9 months ago.
I managed to get every other error ironed out, but I am stuck with this error! For the life of me, I cannot seem to diagnose where I went wrong. Any help from you brilliant people out there would be amazing!
I made a form editing php where it is supposed to edit a submission made into the system. This is then processed by my processing php but for some reason I am getting a "header may not contain more than a single header" error in my form submission. I changed the header code multiple times but I do not know why I am still getting it: https://imgur.com/reX4Yyb
Edit:
Also wanted to add that this code was working fine for about a month. The only thing I changed was updating the hosting service platform from PHP 7.3 -> PHP 7.4. I tried reverting and it exactly the same error.
if($_POST['form_submitted'] == 'editgroupreferral'){
include("../../inc/inc.con.php");
/* assign values to checkboxes */
if(isset($_POST['OtherServices'])){
$otherservices = 1;
} else {
$otherservices = 0;
}
if(isset($_POST['Medication'])){
$medication = 1;
} else {
$medication = 0;
}
if(isset($_POST['HaveAllergies'])){
$allergies = 1;
} else {
$allergies = 0;
}
if(isset($_POST['Device'])){
$device = 1;
} else {
$device = 0;
}
if(isset($_POST['Share'])){
$share = 1;
} else {
$share = 0;
}
if(isset($_POST['TakeTurns'])){
$taketurns = 1;
} else {
$taketurns = 0;
}
if(isset($_POST['Wait'])){
$wait = 1;
} else {
$wait = 0;
}
if(isset($_POST['MultInstructions'])){
$multinstr = 1;
} else {
$multinstr = 0;
}
if(isset($_POST['SitChair'])){
$sitchair = 1;
} else {
$sitchair = 0;
}
if(isset($_POST['Routine'])){
$routine = 1;
} else {
$routine = 0;
}
/* insert vars from form into ReferralSC table */
$sql = "UPDATE ReferralGR SET
ReferrerName = :refname,
ReferrerRelationship = :refrelationship,
ReferrerPhone = :refphone,
ReferrerEmail = :refemail,
ReferMethod = :refmethod,
RefSupport = :refsupp,
OtherServices = :otherservices,
School = :school,
Diagnosis = :diagnosis,
Medication = :medication,
MedicationList = :medicationlist,
HaveAllergies = :allergies,
AllergiesList = :allergieslist,
Device = :device,
Share = :share,
TakeTurns = :taketurns,
Wait = :wait,
MultInstructions = :multinstr,
SitChair = :sitchair,
Routine = :routine,
ExplainFurther = :explain,
HeardAbout = :heardabout,
RefNotes = :notes
WHERE ref_id = :grid";
$s = $pdo->prepare($sql);
$s->bindvalue(':refname', $_POST['ReferrerName']);
$s->bindvalue(':refrelationship', $_POST['ReferrerRelationship']);
$s->bindvalue(':refphone', $_POST['ReferrerPhone']);
$s->bindvalue(':refemail', $_POST['ReferrerEmail']);
$s->bindvalue(':refmethod', $_POST['ReferMethod']);
$s->bindvalue(':refsupp', $_POST['RefSupport']);
$s->bindvalue(':otherservices', $otherservices);
$s->bindvalue(':school', $_POST['School']);
$s->bindvalue(':diagnosis', $_POST['Diagnosis']);
$s->bindvalue(':medication', $medication);
$s->bindvalue(':medicationlist', $_POST['MedicationList']);
$s->bindvalue(':allergies', $allergies);
$s->bindvalue(':allergieslist', $_POST['AllergiesList']);
$s->bindvalue(':device', $device);
$s->bindvalue(':share', $share);
$s->bindvalue(':taketurns', $taketurns);
$s->bindvalue(':wait', $wait);
$s->bindvalue(':multinstr', $multinstr);
$s->bindvalue(':sitchair', $sitchair);
$s->bindvalue(':routine', $routine);
$s->bindvalue(':explain', $_POST['ExplainFurther']);
$s->bindvalue(':heardabout', $_POST['HeardAbout']);
$s->bindvalue(':notes', $_POST['RefNotes']);
$s->bindvalue(':grid', $_POST['ref_id']);
$s->execute();
header('location:../refer_gr/referral-view.php?rid=' . $_POST['ref_id'] );
}
This warning occurs to indicate that you might have a new line [/n] in the string content of your variables. The solution is to strip out the passable new line contents of the variable Like this
$val=$_POST['ref_id'];
$url="../refer_gr/referral-view.php?rid='$val'";
$url=str_replace(PHP_EOL, '', $url);
header("Location: $url");
Okay, this one was a toughie but I figured it out. Here is my method:
So the clue lies in the error itself. It was pointing me from my processing php. But it was only because the data being asked in the header (requires a reference ID) is wrong.
The problem was in the reference ID (after much debugging). It was taking the wrong value from the wrong variable. This was in the php form page not the php processing page.
So here is the solution:
$s->bindvalue(':refid', $refid);
Rest of the code:
<input type="hidden" name="ref_id" value="<?php echo $rid; ?>" >
The variable $rid is not the same as the variable $refid.
Here is the fix:
<input type="hidden" name="ref_id" value="<?php echo $refid; ?>" >
This means that with this type of error, it might be worth looking at which part of the code it is trying to get the value from and start debugging from there.
Thanks for the help everyone!

avoid repeating variable due to undefined variable error

I'm trying to make a profile completion progress, which shows the percentage of how much a user has completed his profile settings. If a user has filled in a field, he receives +15 or +5, however, if the field is not filled in he receives +0.
the code I did is really bad, with variable repetitions, I wanted to know if you knew a cleaner way to do this.
if (!empty($user->avatar)) {
$avatar = 15;
} else { $avatar = 0; }
if (!empty($user->copertina)) {
$copertina = 15;
} else { $copertina = 0; }
// dati personali
if (!empty($user->name)) {
$name= 5;
} else { $name = 0; }
if (!empty($user->last_name)) {
$last_name = 5;
} else { $last_name = 0; }
[...]
if (!empty($user->biografia)) {
$biografia = 5;
} else { $biografia = 0; }
$personal = $avatar+$copertina+$name+$last_name+$sesso+$nascita;
$gaming = $steam+$battlenet+$xbox+$playstation+$switch+$uplay+$origin+$ds;
$social = $twitter+$facebook+$biografia;
$punti = $personal+$gaming+$social;
how do I remove all the others {$ variable = 0}?
You can't really, since you want the value to be a number, and not "undefined". You could initialize your variables to 0 like in this answer stackoverflow.com/questions/9651793/….
If you want to get into type comparisons for null variables, check php.net/types.comparisons. I would just initialize the variables to 0 and remove all the else.
OR...
modify your $user object to have all these variables in an array ($key:$value). You can then initialize the array to 0 all over, and modify it. Adding a new profile value would be easy, and adding array values is quick.
This snippet :
if (!empty($user->avatar)) {
$avatar = 15;
}
else {
$avatar = 0;
}
is semantically equivalent to :
$avatar = (bool)$user->avatar * 15;
Explanation:
Non-empty field gets converted to true and empty string or null gets converted to false
Because we do multiplication php true/false values gets converted to 1/0
So after multiplication you get 15 * 1 or 15 * 0 - depending if your field was used or not.

Auto increment function does not accept 0 as starting number

I created a small function that helps me build an array (i use it to populate a select2 element). It works great but it doesn't accept 0 as the starting number.
Although it is not really crucial i would really want to understand why this happens and how to fix it.
Here is the function:
function create_numstring_array($startNum, $endNum, $jumps, $sideString = NULL) {
if($startNum && $endNum) {
$data = array();
$counter = intval($startNum);
while($endNum > $counter ) {
$data["$counter"] = $counter.' '.$sideString;
$counter = $counter + $jumps;
// echo $counter."<br />";
}
return $data;
}
}
/* DOESNT WORK
echo '<pre>Code:'."<br />";
print_r(create_numstring_array(0, 9, 0.5, ''));
echo '</pre>'."<br />";
*/
/* WORKS! */
echo '<pre>Code:'."<br />";
print_r(create_numstring_array(1, 9, 0.5, ''));
echo '</pre>'."<br />";
I guess it gets stuck in this part
while($endNum > $counter) {
Since $counter = 0 but how can i overcome this?
Because (bool)0 == False. So, your code fails, because you are testing $startNum and it is treated as boolean false.
Change it to something more reasonable, for example: if (is_int($startNum) ... or functions like that (is_numeric could be candidate)
function create_numstring_array($startNum, $endNum, $jumps, $sideString = NULL){
#check for valid input
#(can be float or integer so lets end always greater than start)
if($startNum>$endNum || !is_numeric($jumps)) {
return null;
}
#create the range
$keys = range($startNum, $endNum, $jumps);
#create values with or without sideString
$values = ($sideString)
? array_map(function($a) use ($sideString){ return $a.' '.$sideString;},$keys)
: $keys;
#return the new array
return array_combine($keys,$values);
}
echo '<pre>Code:'."<br />";
print_r(create_numstring_array(0, 9, 0.5, ''));
echo '</pre>'."<br />";
Why your version is not working, is explained in the comments, so here a working version, that check for valid input and valid jumbs. (Works with float and integer). Remove/Skipp last and first entry is they are not needed.

Comparing issues with values php

I have a problem with comparing 2 values and let 1 value change within the if statement. But ofcourse when I reload the page it picks up the first value again. I'm using this code to set some information in a database when a machine is turned on or off.
$urlMachineON = 'http://192.168.0.150/awp/Shredder/PLCfiles/IOmachineActive.html';
// get content
$contentMachineON = file_get_contents($urlMachineON);
//remove first 2 characters
$truncate = substr($contentMachineON, 2);
//remove last 5 characters
$MachineOn = substr($truncate, 0, -5);
//MachineON can only be 1 or 0
$currentState = 2;
if ($MachineOn != $currentState)
{
$stmt = $conn->prepare("INSERT INTO machineactiviteit (Time, MachineStatus) VALUES(NOW(), ?)");
$stmt->bind_param('s', $MachineOn);
if ($stmt->execute() === TRUE)
{
$currentState = $MachineOn;
echo 'success';
}
else
{
echo $conn->error;
}
$stmt->close();
}
elseif($MachineOn == $currentState)
{
echo 'do nothing';
}
So when I do this he will always use the if statement since the $currentState and $MachineOn are always different from each other. In C# you have something like initalize component to set the value one time to a specific value. But I haven't found anything about that in php. So my question is can I set a value only once? Or should I solve this another way?
This is how it should work:
first attempt before: currentState = 2; MachineOn = 0; after: currentState= 0; MachineOn = 0;
second attempt before: currentState= 0; MachineOn = 0; after: currentState= 0; MachineOn = 0;
third attempt before: currentState= 0; MachineOn = 1; after: currentState= 1; MachineOn = 1; (I can change the MachineOn value with a button).
Just save $currentState value somewhere. For example in file or in database.
$currentState = file_get_contents('filepath'); // last saved state (check if is set!)
if($currentState !== $MachineOn) {
file_put_contents('filepath', $MachineOn); // Save current state
} else {
file_put_contents('filepath', 2); // Save other state
}
This is pseoudocode. Remember to check if file exist and has value.

Baffled as to why PHP is giving simple logic error on if statement

Like the title says, PHP is really confusing me on a simple if comparison statement that's returning the opposite of what it should be returning. I'm trying to compare 2 datetime's that are first converted to strings:
//Fetched db query, this returns 2012-06-23 16:00:00
$databaseDateTime = strtotime($row['time']);
//This now returns 1340481600
//today's date and time I'm comparing to, this returns 2012-06-22 17:14:46
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
//this now returns 1340399686
Great, everything works perfect so far. Now here's where things get hairy:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
And this returns 'past', which of course it shouldn't. Please tell me I'm missing something. My project kind of depends on this functionality being airtight.
**EDIT***
Thanks guys for taking the time to help me out. Let me post the entire code because a few of you need more context. The request is coming from an IOS5 to my backend code and json is being sent back to the phone.
<?php
//all included files including $link to mysqli_db and function sendResponse()
function getEvents($eventType, $eventArray) {
global $link;
global $result;
global $i;
global $todaysDateTime;
foreach ($eventArray as $key => $value) {
$sqlGetDeal = mysqli_query($link, "SELECT time FROM deals WHERE id='$value' AND active='y' LIMIT 1") or die ("Sorry there has been an error!");
while ($row = mysqli_fetch_array($sqlGetDeal)) {
//compare times to check if event already happened
$databaseDateTime = strtotime($row['time']);
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
$result[$i] = array(
'whenDeal' => $eventType,
'time' => $databaseDateTime,
);
$i++;
}//end while
}//end foreach
}
if (isset($_GET['my'])) {
//$_GET['my'] comes in as a string of numbers separated by commas e.g. 3,2,6,3
$myDeals = preg_replace('#[^0-9,]#', '', $_GET['my']);
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
$result = array();
$kaboomMy = explode(",", $myDeals);
$i = 1;
if ($myEvents != "") {
getEvents('future', $kaboomMy);
}//end if
sendResponse(200, json_encode($result));
} else {
sendResponse(400, 'Invalid request');
} //end $_POST isset
?>
Found a quick hack around the issue. I just added a local variable to my function and rearranged my compare statement
//added local variable $eventTyppe to function
$eventTyppe;
changed compare from:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
to:
if ($todaysDateTime < $databaseDateTime ) {
$eventTyppe = $eventType;
} else {
$eventTyppe = 'past';
}
Notice if I rearrange compare:
if ($databaseDateTime < $todaysDateTime ) {
$eventTyppe = 'past';
} else {
$eventTyppe = $eventType;
}
I still get the same error. This is the weirdest thing I've ever seen and the first PHP bug I've run into (I'm assuming it's a PHP bug).
Could you print the values of the times right before this line?
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
Since that one is declared as global I'm wondering if is it coming back incorrectly.

Categories