validating array params via function - php

Why does myFunction() below validate the given parameter as true? This was caught by mistake as myFunction should normally receive the entire array as a parameter, but in this case only a specific value ("35") within the array was passed to the function. Yet, it still validated as true. What am I missing here as I would not expect the parameter to validate as true, it was passed a string, not an array?
$myVar = array('id' => '35');
myFunction($myVar['id']);
function myFunction($params) {
if (isset($params['id']) && !empty($params['id']) && $params['id'] == intval($params['id']) && $params['id'] > 0) {
echo "id is valid<br>";
echo "id = " . $params['id'] . "<br>";
echo "params = " . $params . "<br>";
print_r($params);
} else {
echo "id is invalid";
}
}
Output:
id is valid
id = 3
params = 35
35

You are not using strict comparison here $params['id'] == intval($params['id']) and PHP juggles with the types. Change it to $params['id'] === intval($params['id']).
Or use is_int() function.

Related

How to check if value is empty in PHP [JSON]

I have some JSON parameters, that I want to validate if the value are empty with an IF statement. I have written an IF statement in a function to check, but the IF statement only checks for the parameter, I want to check for the values if they are empty. Please, how do I go about this.
my code
//api.php
$payment_type = $this->validateParameter('payment_type', $this->param['payment_type'], STRING, true);
$date_of_delivery = $this->validateParameter('date_of_delivery', $this->param['date_of_delivery'], STRING, true);
$your_generated_waybill_number = $this->validateParameter('your_generated_waybill_number', $this->param['your_generated_waybill_number'], STRING, true);
"payment_type" - is an example of parameter || "1" - is an example of value
{
"name":"create_insert_new_delivery",
"param":{
"payment_type":"1",
"date_of_delivery":"", //E.g here want to check if the value is empty
"your_generated_waybill_number":"39ei40909444567avaab",
}
}
//rest.php
public function validateParameter($fieldName, $value, $required = true){
if($required == true && empty($value) == true){
$this->throwError(EMPTY_PARAMETER, $fieldName . " parameter is missing"); //HERE check if the parameter is missing and fires error, but I also want to include value check
} else if ($required == true && empty($fieldName) == true){
$this->throwError(API_PARAM_REQUIRED, $fieldName . " value is required");
} else {
} //check when parameter is present but value is empty and leave if it is not required
}
testing your variable should be done by using the identity operator.
if (!$var){}
or
if ($var === null){} //checks by type
or
if (empty($field)){}
With empty() function you check for the value
$str = '';
// or
$str = null;
// or
$str = false;
var_dump(empty($str)) // output => true
To check if a variable is defined you can use isset
http://php.net/manual/ro/function.isset.php
You may make your function a little clearer since the tests you are doing will already return true or false. There is no need to compare them to true.
if ($required AND empty($value)) {
$this->throwError(EMPTY_PARAMETER, $fieldName . " parameter is missing"); //HERE check if the parameter is missing and fires error, but I also want to include value check
} elseif ($required AND empty($fieldName)) {
$this->throwError(API_PARAM_REQUIRED, $fieldName . " is required");
} elseif (!empty($fieldName) AND empty($value)) {
$this->throwError(API_PARAM_REQUIRED, $fieldName . " value is required");
}
}
You're main problem is that you're passing the value (grabbed from the array) to the method and checking that. Because at that point, if the array key is not set, a warning is triggered and the value is coerced to null.
empty(): Will return true when the variable is not set OR if it evaluates to some falsey value (e.g. false, null, [], "", etc)
isset(): Will return true ONLY if the value is not set.
So:
$a = ['one' => false];
empty($a['one']); //true
isset($a['one']); //true
isset($a['two']); //false
So you could edit you validation function like so:
public function validateParameter($fieldName, &$inputArray, $required = true){
if($required){
if(!isset($inputArray[$fieldName])){
$this->throwError(EMPTY_PARAMETER, $fieldName . " parameter is missing");
} else if (empty($inputArray[$fieldName])){
$this->throwError(API_PARAM_REQUIRED, $fieldName . " value is required");
}
} else {
if(!isset($inputArray[$fieldName])){
return null;
}
}
return $inputArray[$fieldName];
}
Note: since you are checking a class attribute $this->param. You may avoid passing the array to the method and just reference $this->param in the function, unless it should be more reusable.
I didn't completely understand you desired result in the missing block, but made a reasonable assumption

PHP API request limitation doesn't work

I found this very interesting project on github: https://github.com/brannondorsey/apibuilder
After starting using it, I noticed that the request limitation won't work properly. The value for the requests in the MySQL database counts to "1000" (or the limit set in $hits_per_day), but the API output is still some data from the database.
The expected error message is simply attached to the API response.
But I would like to have an API that doesn't allow any output and only the error message. Below you can find the concerning file.
public function get_json_from_assoc(&$get_array){
$json_obj = new StdClass();
$pretty_print = $this->pretty_print;
if(!$this->find_config_errors()){
if(isset($get_array['pretty_print'])){
if(strtolower($get_array['pretty_print']) == "true") $pretty_print = true;
if(strtolower($get_array['pretty_print']) == "false") $pretty_print = false;
}
//if API is public or if API is private and a correct private key was provided
if(!$this->private ||
$this->private &&
isset($get_array['private_key']) &&
$this->private_key == $get_array['private_key']){
$query = $this->form_query($get_array);
if($this->check_API_key()
|| !$this->API_key_required){
//if search was included as a parameter in the http request but it isn't allowed in the api's config...
if(isset($get_array['search']) &&
!$this->search_allowed){
$json_obj->error = "search parameter not enabled for this API";
}
else if(isset($get_array['exclude']) &&
!$this->exclude_allowed){
$json_obj->error = "exclude parameter not enabled for this API";
}else{
if($results_array = Database::get_all_results($query)){
if(is_array($results_array)){
// deletes key => value pairs if the value is empty. Only works if array is nested:
// http://stackoverflow.com/questions/5750407/php-array-removing-empty-values
$results_array = array_filter(array_map('array_filter', $results_array));
foreach($results_array as $result_array){
foreach($result_array as $key => $value){
if($key == "COUNT(*)"){
$count = $value;
break;
}
}
}
if(!isset($count)) $json_obj->data = $results_array;
else $json_obj->count = $count;
//COME BACK need to make count only parameter work
}
}else $json_obj->error = "no results found";
}
//only attempt to increment the api hit count if this method is called from a PUBLIC API request
if($this->API_key_required){
$query = "SELECT " . $this->API_hit_date_column_name . " FROM " . Database::$users_table . " WHERE " . $this->API_key_column_name . " = '" . $this->API_key . "' LIMIT 1";
$result = Database::get_all_results($query);
//increments the hit count and/or hit date OR sets the error message if the key has reached its hit limit for the day
if($this->update_API_hits($this->API_key, $result[0][$this->API_hit_date_column_name]) === false){
$json_obj->error = "API hit limit reached";
}
}
}else $json_obj->error = "API key is invalid or was not provided";
//if there was a search and it returned no results
if($this->search != "" &&
!$this->search_has_been_repeated &&
isset($json_obj->error) &&
strstr($json_obj->error, $this->no_results_message) == true){
$this->search_in_boolean_mode = true; //set search in boolean mode to true
$this->search_has_been_repeated = true; //note that the search will now have been repeated
//$this->JSON_string = $this->get_json_from_assoc($get_array, $object_parent_name); //recurse the function (thus re-searching)
return $this->get_json_from_assoc($get_array); //recurse the function (thus re-searching)
}
}else{ //API is private but private_key is invalid or was not provided
$json_obj->error = "this API is private and the private key was invalid or not provided";
}
}else{ //config errors were present
$pretty_print = true; //always output errors in pretty print for readability
$json_obj->config_error = $this->config_errors;
}
return ($pretty_print && version_compare(PHP_VERSION, '5.4.0') >= 0) ? json_encode($json_obj, JSON_PRETTY_PRINT) : json_encode($json_obj);
}

get a value from key value pair list in php

I want to display a specific value from key value list..
here is my code:
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
echo "<br/>" . $paramName . " = " . $paramValue;
}
}
ouput
ORDERID = ORDS3700373
TXNAMOUNT = 200.00
CURRENCY = INR
TXNID = 32221284
BANKTXNID = 475815
STATUS = TXN_SUCCESS
RESPCODE = 01
RESPMSG = Txn Successful.
TXNDATE = 2017-01-10 18:13:25.0
GATEWAYNAME = WALLET
BANKNAME =
PAYMENTMODE = PPI
CHECKSUMHASH =
here I want to display only ORDERID and TXNID.. How do I get that value?
You can easily access post values by it's field name instead of looping through all post elements. Simply access that elements directly as below:
if(isset($_POST['ORDERID'])) {
echo 'ORDERID = '.$_POST['ORDERID'];
}
if(isset($_POST['TXNID'])) {
echo 'TXNID= '.$_POST['TXNID'];
}
Moving comments to an answer.
You do not need to loop post it is just a global array. You can access the values at any of the keys like any associative array because that is what it is. Likewise these value can be used like any other
if(isset($_POST['ORDERID'])){
$orderid = $_POST['ORDERID'];
}
if(isset($_POST['TXNID'])){
$txnid = $_POST['TXNID'];
}
// Should use htmlspecialchars() or htmlentities() here
// but didn't want to confuse OP. It is for security.
echo "ORDERID is: " . $orderid . " and TXNID is: " . $txnid;
A note for security never trust user input and sanitize all $_POST variables before echoing or persisting. There are far better article out on the internet than I can summarize here.
You can use if condition in the loop like this
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
if($paramName == 'ORDERID' || $paramName == 'TXNID')
echo "<br/>" . $paramName . " = " . $paramValue;
}
}
add an if like
if($paramName == "ORDERID" || $paramName == "TXNID") {
after foreach, remeber to close it after echo statement line
Don't overcomplicate a trivial task with a loop.
Just drop the loop and echo the two values directly:
// Assuming the two values are expected to come in pair:
if(isset($_POST['ORDERID']) && isset($_POST['TXNID'])) {
echo "<br/>ORDERID = " . $_POST['ORDERID'];
echo "<br/>TXNID = " . $_POST['TXNID'];
}
If you insist on having a loop, then you can go through the property names which you need
foreach(array('ORDERID', 'TXNID') as $paramName) {
if(isset($_POST[$paramName])) {
echo "<br/>" . $paramName . " = " . $_POST[$paramName];
}
}

Variable set to false

I wrote this REALLY simple code:
$foo=false;
echo $foo;//It outputs nothing
Why? Shouldn't it output false? What can I do to make that work?
false evaluates to an empty string when printing to the page.
Use
echo $foo ? "true" : "false";
The string "false" is not equal to false. When you convert false to a string, you get an empty string.
What you have is implicitly doing this: echo (string) $foo;
If you want to see a "true" or "false" string when you echo for tests etc you could always use a simple function like this:
// Boolean to string function
function booleanToString($bool){
if (is_bool($bool) === true) {
if($bool == true){
return "true";
} else {
return "false";
}
} else {
return NULL;
}
}
Then to use it:
// Setup some boolean variables
$Var_Bool_01 = true;
$Var_Bool_02 = false;
// Echo the results using the function
echo "Boolean 01 = " . booleanToString($Var_Bool_01) . "<br />"; // true
echo "Boolean 02 = " . booleanToString($Var_Bool_02) . "<br />"; // false

trying to save time with PHP if/elseif statements

I have a rather big if statement:
if (!$result_spam)
{
$confrim_spam = "FAILED";
}
else if ($result_spam)
{
$confrim_spam = "PASSED";
}
if (!$result_email_manage)
{
$confrim_email_manage = "FAILED";
}
else if ($result_email_manage)
{
$confrim_email_manage = "PASSED";
}
if (!$result_analyt)
{
$confrim_analytics = "FAILED";
}
else if ($result_analyt)
{
$confrim_analytics = "PASSED";
}
Now I want to do another if statement to check if all have PASSED or if all have FAILED or is some have PASSED and some have FAILED and then echo (do something with) the failed ones.
I know how to check if all have passed or failed:
if ($confirm_spam == "PASSED" AND $confirm_analytics == "PASSED"
but to check if some have passed and some haven't and then find the ones that failed will take too long, right?
I was just wondering, would there be an easier/quicker way to do this?
Since they are all bools anyway:
if($result_spam && $result_email_manage && $result_analyt){
//do all passed
}
elseif($result_spam || $result_email_manage || $result_analyt){
//at least one passed
if(!$result_spam){ echo '$result_spam failed';}
if(!$result_email_manage){ echo '$result_email_manage failed';}
if(!$result_analyt){ echo '$result_analyt failed';}
}
else {
//do all failed
}
You can change validation logic to something like
$passed = array();
$failed = array();
if (!$result_spam)
{
array_push($failed, "confirm_spam");
}
else
{
array_push($passed, "confirm_spam");
}
...
Then you have an easy and clear way to check whether all passed/failed and which tests are failed.
What if you try this way:
$passed = $failed = "";
$all = array("confrim_spam" => $result_spam,
"confrim_email_manage" => $result_email_manage,
"confrim_analytics" => $result_analyt);
foreach($all as $a => $b)
{
if (!$b)
$failed.= $a . ", ";
else
$passed.= $a . ", ";
}
Then if var $passed is empty, none passed else if $failed is not empty, at last one have not passed.. so do you got what passed and what failed and do something with them. And you can store results both in a string or an array whatever you want...

Categories