Non-existent constant return true - php

Each time user logs in, I extract a serialized array containing rights. When I unserialize the array and try to assign each right to a constant, non-existent constants return TRUE. For instance, here is my call to database :
$req_level = $pdo->prepare('SELECT * FROM users_levels WHERE level_id = ?');
$req_level->execute(array($row['level_id']));
$row_level = $req_level->fetch();
$user_level_name = $row_level['name'];
$permissions = unserialize($row_level['permissions']);
foreach ($permissions as $permission) {
define(strtoupper($permission), 1);
}
$req_level->closeCursor();
My array ($permissions) is :
Array ( [0] => users_read [1] => users_update [2] => customers_read [3] => customers_update )
When I call all possible constants I should get TRUE for those existing and FALSE for those non existing, but here is what I got...
USERS_READ : <?=USERS_READ?> <br/>
USERS_UPDATE : <?=USERS_UPDATE?> <br/>
USERS_CREATE : <?=USERS_CREATE?> <br/>
USERS_DELETE : <?=USERS_DELETE?> <br/>
When I echo constants...
USERS_READ : 1
USERS_UPDATE : 1
USERS_CREATE : USERS_CREATE
USERS_DELETE : USERS_DELETE
So everything returns TRUE in this case.
Any idea ?

Typically, in PHP, constants that are not found are turned into strings with the same name. So, trying to use a constant 'USERS_READ' becomes the string 'USERS_READ' when attempted to be used. The string 'USERS_READ' when converted to boolean will be true.
So, you need to use the method defined in order to check if it exists before trying to evaluate the constant:
http://php.net/manual/en/function.defined.php
Or, you could do something like this:
function userHasPermission( $permission ) {
return constant($permission) === 1;
}
BTW - on a side note, using "dynamic constant" sounds like a design idea you might want to rethink. Constants are usually constant :)

Related

How to assign value if not increment? laravel

I want to assign a value if not exist else increment the value. Below is the one line code that I'm trying to achieve.
session()->put(['validation_count' => session('validation_count')++ ?? 1]);
But I end up this error below.
Can't use function return value in write context
Someone knows the perfect one line solution?
$validationCount = session('validation_count');
session()->put(['validation_count' => ($validationCount ? $validationCount++ : 1]);
Update for comment:
I recommend with variable usage but if you want to one line:
session ()->put ( ['validation_count' => ( session ( 'validation_count' ) ? session ( 'validation_count' ) + 1 : 1 )] );
session ()->save ();
In one line, you can do like so:
session()->put(['validation_count' => (session('validation_count') ? session('validation_count') + 1 : 1)]);

PHP class to find value in array from session

I am trying to make a simple class that I can use to check if a value exists within an array. There is a session that contains multiple tool values. I am trying to pass the toolID to this function as well as a key and see if that value exists.
Session Data:
Array
(
[keyring] => Array
(
[tool] => Array
(
[toolID] => 1859
[keys] => Array
(
[0] => 49
[1] => 96
)
)
)
)
class Keyring
{
public function checkKey($key, $toolID){
$keyring = $_SESSION['keyring'];
if(isset($keyring)){
foreach($keyring['tool'] as $k => $v) {
if($k == 'toolID' && $v == $toolID){
if (in_array($key, $k->keys)){
return true;
}
}
}
}
return false;
}
}
$keyring = new Keyring();
print_r($keyring->checkKey(49, 1859));
In this example, I am trying to see if key 49 exists in the session for tool 1859.
I am getting the following error : Warning: in_array() expects parameter 2 to be array, null given in.
Is there a better approach for this? All I am looking for is a true/false as to whether that key exists in the keys array for the specified tool.
For my code to work for you may need to change your array a bit or change the code a bit, but rather then looping through a bunch of keys trying to find the right one we are just looking for the keys in the array if they are not set, then return false, or if we find keyring - tools - $tool_id - key_{$key_id} we are just going to return that value, if key_49 = false the function returns false. This should be a tad bit quicker to run on the server for you.
function has_keyring($tool_id, $key_id)
{
//Just to keep the code tidy let's store the tools key in $tool variable
$tool = $_SESSION['keyring']['tools'];
if(isset($tool[$tool_id]) && isset($tool[$tool_id]["key_{$key_id}"]))
return $tool[$tool_id]["key_{$key_id}"];
return false;
}

array_filter to check for conditions?

Can i use array_filter to check for specific conditions in a multidimensional array to replace an if() statement?
Want it to replace something like this:
if($item[0] == $key && $item[1] == "Test"){
//do something here....
}else{
//some other code here...
}
Current Array:
Array
(
[Zone] => Array
(
[Type] => s45
[packageA1] => Array
(
[level] => REMOVE FROM DB
[stage] => REMOVE FROM DB
[description] => description goes here
[image] => NULL
)
)
)
I want to search FIRST to see if [Type] exists. If it DOESN'T exist then i think ill use array_splice to insert it into the existing array. If it DOES exist then ill check if [packageA1] exists, if [packageA1] DOESN'T exist then i'll use array_splice once again. If [packageA1] DOES exist then ill skip over any type if inserting..
Does that make sense?
array_filter is designed for filtering arrays, not replacing boolean logic based on the contents of arrays.
array_filter takes 2 parameters - input and callback.
The callback function should take a single parameter (an item from the array) and return either true or false. The function returns an array with all of the items which returned false removed.
(If no callback function is specified, all items equal to false will be removed from the resulting array.)
Edit:
Based on your updated text, the below code should do what you want:
if (!$item['Zone']['Type']) {
$item['Zone']['Type'] = $something;
}
if (!$item['Zone']['packageA1']) {
!$item['Zone']['packageA1'] = $something;
}
Obviously you need to replace $something with what you actually want to add.
This code could be shortened by the use of ternary operators.
If you are running PHP 5.3 or greater you can do the following:
$item['Zone']['Type'] = $item['Zone']['Type'] ?: $something;
$item['Zone']['packageA1'] = $item['Zone']['packageA1'] ?: $something;
Prior to 5.3 you cannot miss out the middle of a ternary operation and have to use the full format as follows:
$value = conditon ? if_true : if_false;
(When using ?: as in my example, 'condition' and 'if_true' take the same value.)
The full ternary operator (for PHP prior to 5.3) would look like:
$item['Zone']['packageA1'] = $item['Zone']['packageA1'] ? $item['Zone']['packageA1'] : $something;

PHP - warning - Undefined property: stdClass - fix? [duplicate]

This question already has answers here:
PHP check whether property exists in object or class
(10 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I get this warning in my error logs and wanted to know how to correct this issues in my code.
Warning:
PHP Notice: Undefined property: stdClass::$records in script.php on line 440
Some Code:
// Parse object to get account id's
// The response doesn't have the records attribute sometimes.
$role_arr = getRole($response->records); // Line 440
Response if records exists
stdClass Object
(
[done] => 1
[queryLocator] =>
[records] => Array
(
[0] => stdClass Object
(
[type] => User
[Id] =>
[any] => stdClass Object
(
[type] => My Role
[Id] =>
[any] => <sf:Name>My Name</sf:Name>
)
)
)
[size] => 1
)
Response if records does not exist
stdClass Object
(
[done] => 1
[queryLocator] =>
[size] => 0
)
I was thinking something like array_key_exists() functionality but for objects, anything? or am I going about this the wrong way?
if(isset($response->records))
print "we've got records!";
isset() is fine for top level, but empty() is much more useful to find whether nested values are set. Eg:
if(isset($json['foo'] && isset($json['foo']['bar'])) {
$value = $json['foo']['bar']
}
Or:
if (!empty($json['foo']['bar']) {
$value = $json['foo']['bar']
}
In this case, I would use:
if (!empty($response->records)) {
// do something
}
You won't get any ugly notices if the property doesn't exist, and you'll know you've actually got some records to work with, ie. $response->records is not an empty array, NULL, FALSE, or any other empty values.
You can use property_exists
http://www.php.net/manual/en/function.property-exists.php
If you want to use property_exists, you'll need to get the name of the class with get_class()
In this case it would be :
if( property_exists( get_class($response), 'records' ) ){
$role_arr = getRole($response->records);
}
else
{
...
}
Error control operator
In case the warning is expected you can use the error control operator # to suppress thrown messages.
$role_arr = getRole(#$response->records);
While this reduces clutter in your code you should use it with caution as it may make debugging future errors harder. An example where using # may be useful is when creating an object from user input and running it through a validation method before using it in further logic.
Null Coalesce Operator
Another alternative is using the isset_ternary operator ??. This allows you to avoid warnings and assign default value in a short one line fashion.
$role_arr = getRole($response->records ?? null);
The response itself seems to have the size of the records. You can use that to check if records exist. Something like:
if($response->size > 0){
$role_arr = getRole($response->records);
}
If think this will work:
if(sizeof($response->records)>0)
$role_arr = getRole($response->records);
newly defined proprties included too.

How to create wordpress like functions in PHP?

To pass variables into functions, I do the following (as other people I'm sure):
function addNums($num1, $num2)
{
$num1 + $num2;
}
addNums(2, 2);
My question is how would I structure a function to act like Wordpress:
wp_list_categories('title_li=');
Essentially I am looking for a way to create a key/value pair in my functions.
Any advice is appreciated.
parse_str() should do what you want: http://www.php.net/parse_str
You can use parse_str to parse the string for arguments. The tricky thing is that you may not want to just allow any and all parameters to get passed in. So here's an example of only allowing certain parameters to be used when they're passed in.
In the following example, only foo, bar and valid would be allowed.
function exampleParseArgs($arg_string) {
// for every valid argument, include in
// this array with "true" as a value
$valid_arguments = array(
'foo' => true,
'bar' => true,
'valid' = true,
);
// parse the string
parse_str($arg_string, $parse_into);
// return only the valid arguments
return array_intersect_key($parse_into,$valid_arguments);
}
baz will be dropped because it is not listed in $valid_arguments. So for this call:
print_r(exampleParseArgs('foo=20&bar=strike&baz=50'));
Results:
Array
(
[foo] => 20
[bar] => strike
)
Additionally, you can browse the Wordpress Source code here, and of course by downloading it from wordpress.org. Looks like they do something very similar.

Categories