How to sanitize a [null] array input for my API program? - php

I am calling API through postman and passing following parameters.
reason: string
staff_ids[]:
When pass staff_ids blank then I got [null] in server-side.
so that the condition gets always true.
if(isset($request->staff_ids) && !empty($request->staff_ids)){
//
}
Is there any way to check if array has [null]?

Instead of checking, you may simply filter out all NULL values before other works
if (!isset($request->staff_ids) || $request->staff_ids === null) {
$request->staff_ids = array(); // default to empty array if is not set or is null
}
if (!empty($request->staff_ids)) {
$request->staff_ids = array_filter($request->staff_ids, function ($id) {
return ($id !== null);
});
if (!empty($request->staff_ids)) {
// ...
}
}

I have filtered array values before checking as #KoalaYeung Answered. It is working fine.
$request->staff_ids = array_filter($request->staff_ids, function ($id) {
return ($id !== null);
});
if(isset($request->staff_ids) && !empty($request->staff_ids)){
///
}
Is there any better approach?

you can check this with is_null function and sizeof() for array
if(!is_null($request->staff_ids) && sizeof($request->staff_ids)){
}

Related

Shorthand for checking if associative array not null and if key exists

Is there any way of checking if a variable is not null and then to check if variable has nested associative array keys using a shorthand? Something like optional chaining for associative arrays?
Example of what I would like to make concise:
public $arr;
//$arr gets set as an associative array somewhere else in the code.
function someFunc() {
if ($this->arr && $this->arr['key1'] && $this->arr['key1']['key2'] == 'Some Value') { // shorten this line?
// Do Something Cool!
}
}
I am looking for something similar to Optional Chaining in Javascript e.g. :
if (obj.key1?.key2 == 'Some Value') {
// Do something kool
}
There is a high probability that this is a duplicate and I apologize in advance if that is the case. I tried searching for this for associative arrays and could not find anything specific.
You could keep the if statement intact, but replace $this->arr && $this->arr['key1'] with an Null Coalescing Operator (??), so if those aren't defined, it will use the fallback, that isn't equal to the test string:
if (($this->arr['key1']['key2'] ?? false) == 'Some Value') {
// Do Something Cool!
}
So if $this->arr['key1']['key2'] is defined, you'll compare that to Some Value, otherwise, if it's not defined, you'll compare (eg) false to Some Value witch will remain false.
Use the php function isset: https://www.php.net/manual/en/function.isset.php
It will check for multiple keys: if( isset($this->arr['key1']['key2'] ) {...} and also includes a null check.
If you for some reason need to shorten it even more, simply decompose it to another function:
public $arr;
//$arr gets set as an associative array somewhere else in the code.
function someFunc()
{
if ($this->checkForSomeValue($this->arr, 'Some Value', 'key1', 'key2')) { // shorten this line?
// Do Something Cool!
}
}
function checkForSomeValue(array $arr, string $valueToCheck, ...$keys)
{
$valueCompare = $arr;
foreach($keys as $key)
{
if(!isset($valueCompare[$key]))
{
$valueCompare = null;
break;
}
else
{
$valueCompare = $valueCompare[$key];
}
}
return $valueCompare && $valueCompare === $valueToCheck;
}
I've updated the answer to allow supplying keys

Function Return object

I was following a tutorial that I got a problem
function old($field) {
return request($field);
}
function request($field = null) {
$request = new \App\Helper\Request();
if(is_null($field))
return $request;
return $request->input($field);
}
I can't figure out why we should set $filed as null and what happens while using two return?the usage of old function is keeping true values after validation in register menu textboxes
the following source code is request class which manages the requests:
class Request
{
public function input($filed, $post = true)
{
if ($this->isPost() && $post)
return isset($_POST[$filed]) ? htmlspecialchars($_POST[$filed]) : "";
return isset($_GET[$filed]) ? htmlspecialchars($_GET[$filed]) : "";
}
public function all($post = true)
{
if ($this->isPost() && $post)
return isset($_POST) ? array_map('htmlspecialchars' , $_POST) : null;
return isset($_GET) ?array_map('htmlspecialchars' , $_GET) : null;
}
public function isPost()
{
return $_SERVER['REQUEST_METHOD'] == 'POST';
}
}
PS:if someone needs more information, please tell me I will send the complete source code.
Thank you
i can't figure out why we should set $field as null and what happens while using two return?
You are not setting $field to null but $field here is an optional argument that means, if no argument is passed to the function, null will be used as default value.
And then this:
$request = new \App\Helper\Request();
if(is_null($field))
return $request;
return $request->input($field);
simply means, if $field is null then return the result of new \App\Helper\Request() otherwise the result of $request->input($field) where $request=new \App\Helper\Request()
Even if I may have just one single line instruction inside if statement, I prefer to use parenthesis for more readability and best understanding.

PHP function not seeing value of second parameter

For some odd reason my PHP is not seeing the value of the second parameter.
My code:
PHP function:
public function getVacs($key, $id = null, $deleted = null, $deleted_key = null) {
if(!$id) {
$data = $this->_db->getAll('vacatures', $key);
} elseif(!empty($deleted)) {
$data = $this->_db->getAll('vacatures', $key, $id, $deleted, $deleted_key);
} else {
$data = $this->_db->getAll('vacatures', $key, $id);
}
if($data->count()) {
$this->_data = $data->results();
$this->_count = $data->count();
return true;
}
}
Calling the function:
} elseif(isset($_POST['all'])) {
$vacs = $v->getVacs('delete', '0');
echo json_encode($v->data());
exit();
}
The problem is, the function does not see the value of $id.
It's running the first if while it should be running the else.
In php the string "0" evaluates to false.
This means your check if(!$id) will evaluate to true and by your logic id won't be set in $data.
If the string "0" is legitimate option, then check for null explicitly instead:
if(is_null($id)){
This will
It is seeing the value of $id, but your if statement is set up wrong. 0 will evaluate to false on a check like that. So you really need to make sure that it's not null:
if($id != null) {
If you want the first if to run only if there is NOT a valid id, then you need to check if it's empty (i.e. not null, 0, false, or an empty string)
if(empty($id)) {
Using the strict comparison operator might be a good idea in these cases (and I would say in most cases):
0 == null; // evaluates to true
0 === null; // evaluates to false
Useful with strpos also (returns 0 means searched term at position 0 of haystack string, returns false means searched term not found).

PHP return the value but false

I have this simple function:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status']))
return $status['status'];
return false;
}
Now I am looking for a way to return false yes, but to return also the value of the variable.
I tried the following, but it makes it empty anyway:
return $status['status'] == false;
So the logi is return false anyway but give me back also the value of the variable, even if it's false, because false should not mean empty :)
Return an array, and use the list() method to get your results:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
$statusString = $status['status'];
$statusFlag = false;
if(isAllowed($status['status']))
$statusFlag = true;
return array($statusFlag,statusString);
}
//usage
list($flag,$msg) = isMember(5,"whatever");
echo "Access: $flag, with message $msg";
A function can not return multiple values, but similar results can be obtained by (1) returning an array or by (2) passing a variable by reference and storing the value you want returned in that variable.
You will need to write your function in a way that it returns an array containing the following:
The value you wan't returned
A flag that signifies true/false
Pass a variable by reference into your function and store the value of the status in that variable.
function isMember($uID, $pdo, &statByRef) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status'])) {
return $status['status'];
}
$statByRef = $status['status'];
return false;
}
False returns empty in PHP, see http://php.net/manual/en/function.empty.php
From documentation:
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
Try using something like this:
function isMember($uID, $pdo) {
$status = getUserStatus($uID, $pdo);
if(isAllowed($status['status'])){
return $status['status'];
}
return false;
} // If isAllowed returns true, then PHP will return $Status['Status'];, if not then PHP will by default return false.
I have noticed you haven't used braces which makes the code a little awkward to debug. Then validate like:
if (isMember($Var,$AnotherVar) !== false){
//isMember has not returned false, so PHP is operating within these braces
}
Such a simple thing, which should be most effective.
If your wanting to assign true/false to $status['status']; then you are performing the right method, but wrong operator.
== is a comparision operator. Not assignment
= is an assignment operator, so your assignment should be:
$status['status'] = false;

PHP referencing array element (&$array['element']) creates element

I have a function that checks if a variable is exists.
function variable( &$var, $default = NULL )
{
if( (!isset($var) && !is_array($var)) || empty($var) )
{
return FALSE;
}
elseif( is_array($var) && count($var) <= 0 )
{
return FALSE;
}
else
{
return $var;
}
}
My problem is, that this function creates an array when I pass an array element reference like $array['element'] the array $array and the index 'element' is created even if it did not exists before.
What the function is supposed to do is having something like echo variable($var); which does no produce an error even if $var is not defined.
Is there a way to delete this again or even better not let the function create the array?
Thanks.
See here: http://ch.php.net/manual/de/function.array-key-exists.php
array_key_exists is the "key", no pun intended :-)
like so:
if (array_key_exists('element', $array)({
// do the fan dango
}
To delete, you can use unset($array['element']); or unset($array); depending on your goal.
For making sure the array turns into a string, just use implode("",$array);

Categories