If else not working with empty variables/Data in PHP - php

I am working wiht RestApi in php and i want to check whether "Post Data" is empty or not with one condition but right now my "else" part is working instead of "if",Where i am wrong ? Here is my code
$email = $this->input->post('otpEmail');
$one = $this->input->post('one');
$two= trim($this->input->post('two'));
$three= trim($this->input->post('three'));
$four= trim($this->input->post('four'));
if(empty($email) && empty($one) && empty($two) && empty($three) && empty($four)) {
$responseJSON = array("Status" => false, "Message" => "Please enter your otpEmail,one,two,three,four");
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
else
{
$responseJSON = array("Status" => true, "Message" => "All data exist here");
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}

Try this as your code seems logically incorrect ( replace && with || )
if(empty($email) && empty($codeBox1) && empty($codeBox2) && empty($codeBox3) && empty($codeBox4)) {
}else{
}

Related

PHP unreachable if statement in foreach

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 />";
}
}
}
}

Apple Wallet not giving Push Token to Web Service

I have a Pass for Apple Wallet with a webServiceURL specified which I am currently trying to get working. So far, I can tell if the pass is added or deleted, after verifying with Auth Token and I get the correct Device ID as well as Serial Numbers. However, the value of $_POST is an empty array when the pass is added, so I cannot get the Push Token. Is there something I am missing? Here is my PHP.
<?php
function unauthorized() {
header('HTTP/1.1 401 Unauthorized');
exit;
}
$headers = apache_request_headers();
if (isset($headers['Authorization']) && strpos($headers['Authorization'], 'ApplePass') === 0 && strpos($_SERVER['PATH_INFO']) !== false) {
$pathInfo = $_SERVER['PATH_INFO'];
if ($pathInfo[0] === '/') { $pathInfo = substr($pathInfo, 1); }
$parameters = explode('/', $pathInfo);
if ($parameters[0] !== 'v1' || $parameters[1] !== 'devices' || $parameters[3] !== 'registrations' || $parameters[4] !== 'MYPASSIDENTIFIER') {
unauthorzed();
exit;
}
$deviceId = $parameters[2];
$passSerial = $parameters[5];
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// User deleted pass
} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// User added pass
$payload = json_decode($_POST);
// $_POST is empty array, and $payload is always nothing
} else {
// Something fishy
unauthorized();
}
} else {
unauthorized();
}
Try using the REQUEST_URI and read the body with php://inpupt
$headers = apache_request_headers();
$request = explode("/", substr(#$_SERVER['REQUEST_URI'], 1));
if (strtoupper($_SERVER['REQUEST_METHOD']) === "POST"
&& isset($headers['Authorization'])
&& (strpos($headers['Authorization'], 'ApplePass') === 0)
&& $request[1] === "devices"
&& ($request[3] === "registrations") {
$auth_key = str_replace(array('ApplePass '), '', $headers['Authorization']);
$device_id = $request[2];
$pass_id = $request[4];
$serial = $request[5];
$dt = #file_get_contents('php://input');
$det = json_decode($dt);
// Process Device Token

Saving to a file in PHP

I have to save unique passwords and usernames to a file, but my code duplicate the first two entries, then start working properly from there. here's my code. What am I missing? I using Mac with MAMP. I'm testing the code using curl with this command curl -d login=tenten -d passwd=peter -d submit=OK 'http://localhost:8080/php/create.php'
function user_exist($user_array, $user_name)
{
foreach ($user_array as $user) {
if ($user['login'] === $user_name)
return (TRUE);
}
return (FALSE);
}
if ($_POST['submit'] === 'OK')
{
if ($_POST['passwd'] != "" && $_POST['login'] != "")
{
create_file('../private');
if (file_exists('../private/passwd'))
{
$hash_passwd = hash('whirlpool', $_POST['passwd']);
$passwds = unserialize(file_get_contents('../private/passwd'));
if (!user_exist($passwds, $_POST['login']))
{
$passwds[] = array('login' => $_POST['login'], 'passwd' => $hash_passwd);
$serialize = serialize($passwds);
file_put_contents('../private/passwd', $serialize);
echo "OK\n";
}
else
{
echo "ERROR\n";
}
}
else
{
$hash_passwd = hash('whirlpool', $_POST['passwd']);
$user_cred = array('login' => $_POST['login'], 'passwd' => $hash_passwd);
$serialize = serialize($user_cred);
file_put_contents('../private/passwd', $serialize);
echo "OK\n";
}
}
else
{
echo "ERROR\n";
}
}
else
{
echo "ERROR\n";
}

php cannot validate if fields are set

When I submit empty fields, it displays "Something has gone wrong" instead of "All fields are required.". Could you help me to find my mistake please.
PHP file:
<?php
if(!isset($_POST['name']) ||
!isset($_POST['email']) ||
!isset($_POST['order'])) {
$data = array(
'message' => "All fields are required."
);
echo json_encode($data);
}
?>
You conditions in PHP file are wrong. Use this instead
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['order'])) {
$data = array('message' => "Message A");
echo json_encode($data);
}else{
$data = array('message' => "All fields are required");
echo json_encode($data);
}
I use && for required values. You can use && or || according to your need.
Update
if(!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['order'])) {
$data = array('message' => "All fields are required");
echo json_encode($data);
}else{
// whatever you want to do, if all values available, goes here
}
Try this:
<?php
if(!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['order'])) {
echo "No post values found!";
}
else{
$data = array('message' => "Message A");
echo json_encode($data);
}
?>
Instead of using !isset() try using empty().

JSON from PHP file result was code, do not text

I have code PHP in file update_customer.php to save information customer
<?php
date_default_timezone_set('Asia/Ho_Chi_Minh');
$response = array( 'status' => 0, 'message' => '', 'typeinsurance' => '', 'thoigianmua' => 0 );
if (empty($_GET) && !empty($_POST) && count($_POST) == 7 && isset($_POST['fullname']) && isset($_POST['email']) &&
isset($_POST['address']) && isset($_POST['phone']) && isset($_POST['cost']) && isset($_POST['typeinsurance']) &&
isset($_POST['typepay']))
{
require_once ('./../include/database.php');
$database = new Database();
$time = time();
$_POST['thoigianmua'] = $time;
if ($database->insert('customer', $_POST)){
$response['status'] = 1;
$response['typeinsurance'] = $_POST['typeinsurance'];
$response['thoigianmua'] = $time;
}
}
echo json_encode($response);
and code JQUERY to sent data, but My JSON get
Object {status: 1, message: "", typeinsurance: "<?php echo $_POST['typeinsurance']; ?>", thoigianmua: 1440642246}
Please help me, thank in advance
You php code has error for sure that's why its returning the data in a way that you not expected.
The wrong part is <?php echo $_POST['typeinsurance']; ?> you have given the php code as string.
you have to check your php file

Categories