PHP unreachable if statement in foreach - php

I have this code I have set up that is supposed to read from JSON and output each array. Except when I use my foreach loop, I have an unreachable if statement. It's supposed to reach it if "type" is "rawbr".
I have confirmed that this has nothing to do with foreach by placing the same message in a row.
I wish to output this:
UnknownUser3: hey hxor? [To you]
Welcome to chat!
Here is my code:
innerchat.php:
<?php
session_start();
function tf($oz){
if($oz == 0){
return false;
} else if($oz == 1){
return true;
}
}
if(isset($_GET["room"]) && file_exists("data/".$_GET["room"].".json")){
$jsonF = file_get_contents("data/".$_GET["room"].".json");
$jsonD = json_decode($jsonF, true);
echo count($jsonD["msg"]);
// echo $jsonD["msg"][1]["type"];
foreach($jsonD["msg"] as $key => $message){
if($message["visibility"] !== "all"){
if(isset($_SESSION["ts_user"]) && $_SESSION["ts_user"] == $message["visibility"] && $message["type"] != "rawbr"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [To you]<br />";
} else if($message["type"] === "message" && $message["visibility"] === "all"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [normal message]<br />";
} else if($message["type"] === "rawbr" && $message["visibility"] === "all"){
echo $message["cont"]."<br />";
}
}
}
}
kb6k.json (the room we're working with)
{"name":"KillerBot 6000","desc":"A room with very harsh moderation. Proceed with caution!","max":600,"color":"#e0e0e0","whispersenabled":true,"forbiddenCommands":["/milk", "/bal"],"msg":[{"cont":"hey, hxor?","time":1,"color":"black","type":"message","visibility":"HxOr1337","from":"UnknownUser1"},{"cont":"Welcome to the chat!","time":0,"type":"message","color":"black","visibility":"HxOr1337","from":"Test"}]}
I know it couldn't possibly do anything to do with the JSON itself, since the other values are nearly identical apart from "visibility"

Ok, so I figured out that I put those if statements in $message["visibility"] !== "all"
The code:
<?php
session_start();
if(isset($_GET["room"]) && file_exists("data/".$_GET["room"].".json")){
$jsonF = file_get_contents("data/".$_GET["room"].".json");
$jsonD = json_decode($jsonF, true);
// echo $jsonD["msg"][1]["type"];
foreach($jsonD["msg"] as $key => $message){
if($message["visibility"] !== "all"){
if(isset($_SESSION["ts_user"]) && $_SESSION["ts_user"] == $message["visibility"] && $message["type"] != "rawbr"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [To you]<br />";
}
} else {
if($message["type"] === "message" && $message["visibility"] === "all"){
echo "<font color='".$message["color"]."'><b><u>".$message["from"].":</u></b></font> ".htmlspecialchars($message["cont"])." [normal message]<br />";
} else if($message["type"] === "rawbr" && $message["visibility"] === "all"){
echo $message["cont"]."<br />";
}
}
}
}

Related

IF else & else if in Codeigniter

please check my script.
if($namachief != NULL)
{
echo $namachief;
}
else if ($namarm != NULL)
{
echo $namarm;
}
else
{
echo "Something wrong. Please contact US";
}
My condition isn't working when in this condition => $namarm != NULL, I only get white page but its normal when in this condition => $namachief != NULL.
It's fine when i do this
echo $namachief; & echo $namarm;
if () {
}
else if (){
}
else if(){
------------------------ My Script Here -----------------------------
}
Both answer below are right. My problem lies here. In my form I did this
<option value="none">None</option> Then i change it to <option value="">None</option>
You try like this
if($namachief != NULL || $namachief != "")
{
echo $namachief;
}
else if ($namarm != NULL || $namarm != "")
{
echo $namarm;
}
else
{
echo "Something wrong. Please contact US";
}
Write your condition as below:-
if(isset($namachief) && !empty($namachief)){
echo $namachief;
}
else if (isset($namarm) && !empty($namarm)){
echo $namarm;
}
else{
echo "Something wrong. Please contact US";
}
If you want to print both variables if both are set and have valid values then,
if(empty($namarm) && empty($namachief)){
echo "Something wrong. Please contact US";
}
else if (!empty($namachief) && !empty($namarm)){
echo $namarm;
echo $namachief;
}
else if (isset($namarm) && !empty($namarm)){
echo $namarm;
}
else if(isset($namachief) && !empty($namachief)){
echo $namachief;
}
else{
// else stuff
}

How to compare value in bidimensional array Laravel

I receive the information with this form correctly.
$findNIF = User::where('nif','=',$nif)->get();
$findEmail = User::where('email','=',$email)->get();
I need to compare if it is the same value the "nif" and "email" of the $findNIF and $findEmail.
$findNIF["0"]["nif"];
$findNIF["0"]["email"];
$findEmail["0"]["nif"];
$findEmail["0"]["email"];
I use the following sentence but I always receive "OK"
if ($findNIF["0"]["nif"] && $findNIF["0"]["email"] && $findEmail["0"]["nif"] && $findEmail["0"]["email"]){
echo "OK";
} else {
echo "NO";
}
Here
if ($findNIF["0"]["nif"] && $findNIF["0"]["email"] && $findEmail["0"]["nif"] && $findEmail["0"]["email"]){
echo "OK";
} else {
echo "NO";
}
in your condition if you get values in both of your $findNIF and $findEmail variables then it always return true.
If you want to compare the nif of $findNIF & $findEmail and email of $findNIF & $findEmail both then this would be like this
if (($findNIF["0"]["nif"] == $findEmail["0"]["nif"]) && ($findNIF["0"]["email"] == $findEmail["0"]["email"])){
echo "OK";
} else {
echo "NO";
}
Please elaborate more about what you need.

PHP weird comparison

I've got two inputs in registration form, one with login, one with password. After calling AJAX I'm trying to validate those data and I'm using function below:
function test_input($data) {
if( $data == $_POST["login"] && $data == "" ){
$GLOBALS["message"] .= "<p>Empty login.</p>";
return;
}
elseif( $data == $_POST["pwd"] && $data == "" ){
$GLOBALS["message"] .= "<p>Empty password.</p>";
return;
}
echo 'Good job.';
}
When I click submit button without writing anything I've got answer:
Empty login
Empty login
When I write something in one of them or both of them validation's ok. Why?
Edit - Missing code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$login = test_input($_POST["login"]);
$pwd = test_input($_POST["pwd"]);
if($message!= ""){
echo $message;
}
else{
echo 'OK';
}
}
Perhaps refactor it something like:
function test_input($data, $field) {
if( $field == "login" && $data == "" ){
return "<p>Empty login.</p>";
}
elseif( $field == "pwd" && $data == "" ){
return "<p>Empty password.</p>";
}
echo 'Good job.';
}
and
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message .= test_input($_POST["login"], "login");
$message .= test_input($_POST["pwd"], "pwd");
if($message!= ""){
echo $message;
}
else{
echo 'OK';
}
}

Multiple else if not working correctly PHP

I'm having an issue with a login script. The rest of it works fine, but there is something odd happening here. The issue is that even though $IPCHK is returning true the elseif function does not execute. It only executes when I set $IPCHK to jibberish. Any help would be great. Thanks in advance
if ($Numrows == 0)
{
if ($Fail >= 3)
{
$Connection = connectToDb();
//return true, false,pending
$IPCHK = checkIP();
$IPCHK = true; //forcing it to be true and still broke
//If no ip id there
if($IPCHK == false)
{
$IP = getIP();
$Query = "INSERT INTO ip VALUES ('','$IP',Now())";
mysqli_query($Connection, $Query)
or die(error(mysqli_error($Connection)));
echo "You have failed to login too many times";
echo "<br />Please <a href='login.php'>try again</a> later.";
$Lock = true;
}
//If ip is there but timer is not up
elseif ($IPCHK == 'pending')
{
echo "You have failed to login too many times";
echo "<br />Please <a href='login.php'>try again</a> later.";
$Lock = true;
}
//Timers Up
elseif ($IPCHK == true) //here does not execute when it returns true
{
$_SESSION['FailedLogin'] = 0;
$Lock = false;
}
else
{
error("End of if check");
}
}
else
{
$Fail = 3 - $Fail;
$_SESSION['FailedLogin'] = $_SESSION['FailedLogin'] + 1;
$Error = $Error."<br />You have ".$Fail." attempts remaining";
}
}
In your Condition you have
elseif ($IPCHK == 'pending')
then
elseif ($IPCHK == true)
the second else will never execute because $IPCHK == 'pending' means also that $IPCHK == true
if you want to execute your second else you have to change the seconde condition to somethig like this
elseif($IPCHK == 'done')
or simply use === like this
elseif($IPCHK === 'pending')
then
elseif($IPCHK === true)
Lamari Alaa is correct, and the relevant documentation entry on type juggling can help understand why.
The following script outputs: boolean = string:
$test = true;
if( $test == 'pending' ) {
echo 'boolean = string';
} else if ( $test ) {
echo 'boolean != string';
}
This is because the string 'pending' is being coerced into a boolean value before being compared to the boolean value true. Since it evaluates as true, the first condition is taken. Consider replacing == 'pending' to === 'pending'

PHP if statement errmsg

I have this if statment
if(!empty($URL) && ($safe===true)){
//lots of code
}
Is it possible to show different error messages depending on what condition failed?
For example if $URL is empty echo "URL empty";
and if $safe===false echo "GTFO";
Just add this to your code
else if(empty($URL)
{
echo "url empty";
}
else if($safe===false)
echo "Get Out"; // be polite ;)
if (empty($url))
{
echo "URL empty";
}
elseif ($safe === false)
{
echo "GTFO";
}
else
{
//lots of code
}
} else {
if($safe === false){
die("GTFO");
}
if (empty($url)){
echo "URL Empty.";
}
}
Yes; you could make use of an else if statement.
if (!empty($URL) && ($safe===true)) {
//lots of code
} else if (empty($URL)) {
// report that url is empty
} else if ($safe === false) {
// report that safe is false
}
Alternatively, you could just use an else statement to report that the if condition was false.
I propose the following solution. It will allow you to show multiple errors and set each condition only once (instead of having so many conditions and anti-conditions as other solutions proposed).
$errors = array();
if(empty($URL) {
$errors[] = 'URL empty';
}
if($safe !== true) {
$errors[] = 'GTFO';
}
if(empty($errors)) {
//lots of code
} else {
echo '<ul>';
foreach($errors as $error_message) {
echo '<li>' . $error_message . '</li>';
}
echo '</ul>';
}

Categories