Is it possible to set multiple session elements to the same session at different times? I have 2 classes and each class should set 2 session elements. What I'm getting back is an empty array. I am using session_start() on each page.
Also, I can set the session successfully from within a single class, but get an empty array back when setting from each class.
// User class
$_SESSION['user'] = array('id' => 1);
$_SESSION['user'] = array('name' => 'Tim Miller');
// Part class
$_SESSION['user'] = array('model' => '12311');
$_SESSION['user'] = array('part' => 'AA34F');
EDIT:
Here is the array I would like to create:
Array (
[user] => Array (
[id] => 1
[name] => Tim Miller
[model] => 12311
[part] => AA34F
[order] => 119026
[serial] => 12001923S3
)
)
Elements 0 and 1 should be set in the user class
Elements 2-3 should be set in the part class
Elements 4-5 should be set in the serial class
You can set it but bit different approach need to be used. You can create an array of sessions with different values.
You have to write session_start() on top of each file where you need to use session.
session_start();
// User class
$_SESSION['user'][] = array('id' => 1);
$_SESSION['user'][] = array('name' => 'Tim Miller');
// Part class
$_SESSION['user'][] = array('model' => '12311');
$_SESSION['user'][] = array('part' => 'AA34F');
print_r( $_SESSION['user'] );
Output looks like:
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[name] => Tim Miller
)
[2] => Array
(
[model] => 12311
)
[3] => Array
(
[part] => AA34F
)
)
It's upto you how do you want to crate this array.
EDIT:
To get your desire format output and add values to array later in different files you can give a try like:
// Your code here!
session_start();
// User class
$_SESSION['user'][] = array('id' => 1, 'name' => 'Tim Miller');
// Part class
$key = -1
$key = array_search( 1, array_column($_SESSION['user'], 'id') );
// Here 1 in array_search is id of user your can use $id to add data to correct user's by id.
if( $key > -1 ) {
$_SESSION['user'][ $key ] = array_merge( $_SESSION['user'][ $key ], array('model' => '12311', 'part' => 'AA34F') );
}
print_r( $_SESSION['user'] );
This will give you following output:
Array
(
[0] => Array
(
[id] => 1
[name] => Tim Miller
[model] => 12311
[part] => AA34F
)
)
Related
It is supposed to be easy but I can not work it out..., you include arg "fields" with value "all_with_meta" and you should get the user metas. My code:
$users = get_users([
'fields' => 'all_with_meta',
'role' => 'colegiado',
'offset' => $start,
'number' => $limit
]);
One of the results (it has metas, but they do not show up):
WP_User Object
(
[data] => stdClass Object
(
[ID] => 4
[user_login] => ccarasm
[user_pass] => **********
[user_nicename] => ccarasm
[user_email] => car*****#****.com
[user_url] =>
[user_registered] => 2021-09-10 09:23:26
[user_activation_key] =>
[user_status] => 0
[display_name] => Cass CM
)
[ID] => 4
[caps] => Array
(
[no_colegiado] => 1
[colegiado_inactivo] => 1
[colegiado] => 1
)
[cap_key] => wp_capabilities
[roles] => Array
(
[1] => colegiado_inactivo
[2] => colegiado
)
[allcaps] => Array
(
[read] => 1
[publish_posts] => 1
[edit_posts] => 1
[level_0] => 1
[frm_view_forms] => 1
[frm_edit_forms] => 1
[frm_view_entries] => 1
[frm_create_entries] => 1
[frm_edit_entries] => 1
[no_colegiado] => 1
[colegiado_inactivo] => 1
[colegiado] => 1
)
[filter] =>
[site_id:WP_User:private] => 1
)
I would like to get all the metas for every user from the query, can anybody help me? Thanks!!!!
** UPDATE: AN ALTERNATIVE TO THE SOLUTION GIVEN BY #Xhynk**
I needed to insert it into wp_user object so I used method get() and added metas to the object:
foreach ($users as $key => $wp_user_object) {
$wp_user_object->data->num_colegiado = $wp_user_object->get('num_colegiado');
$wp_user_object->data->first_name = $wp_user_object->get('first_name');
$wp_user_object->data->last_name = $wp_user_object->get('last_name');
$wp_user_object->data->telefono = $wp_user_object->get('telefono');
$wp_user_object->data->nif = $wp_user_object->get('nif');
}
Unfortunately, according to the Codex entry for WP_User_Query()` , under the return values sections is following:
If ‘fields‘ is set to ‘all’ (default), or ‘all_with_meta’, it will return an array of WP_User objects (does not include related user meta fields even with ‘all_with_meta’ set).
There's also a note in the Parameters section above:
*’all_with_meta’ currently returns the same fields as ‘all’ which does not include user fields stored in wp_usermeta. You must create a second query to get the user meta fields by ID or use the __get PHP magic method to get the values of these fields.
What that means, is that currently (as of this Q/A, with WordPress 5.8.1) you'll need to grab the user meta separately, either with the get_user_meta() function or the magic methods. For instance:
$users = get_users( $args );
foreach( $users as $user ){
// Get All User Meta Fields as array
$all_meta_fields = get_user_meta( $user->ID );
/* OR */
$field_you_want = get_user_meta( $user->ID, 'field_you_want', true );
/* OR */
$field_you_want = $user->key_of_meta_field;
// example: var_dump( $user->rich_editing; ); // Outputs `string(4) "true"`
}
I need help :)
I've to code a script that, cycling through an array inside an array , delete an element if in XXX field there isn't value (is NULL ).
My array is:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[0] => stdClass Object ( [name] => minnie [email] => blabla#gmail.com [XXX] => )
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
In this example the item [0] has no value in XXX value so my output array will be:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
i hope that you can help me :)
You could use a nested foreach() Loop to cycle through the Data and then perform some tests, which on failing, guarantees that it is safe to unset the pertinent variable. Here's how:
<?php
// WE SIMULATE SOME DATA TO POPULATE THE ARRAY, ONLY FOR TESTING PURPOSES
$objDate = new stdClass();
$objRez1 = new stdClass();
$objRez2 = new stdClass();
$objRez1->name = "minnie";
$objRez1->email = "blabla#gmail.com";
$objRez1->XXX = null;
$objRez2->name = null;
$objRez2->email = "fddd#gmail.it";
$objRez2->XXX = 0.88451100;
$objDate->sec = 1468503103;
$objDate->usec = 0;
// IN THE END WE NOW HAVE A SAMPLE ARRAY (SIMULATED) TO WORK WITH.
$arrData = array(
'idCampaign' => 3,
'idIT' => 322,
'recipients' => array(
$objRez1,
$objRez2
),
'date' =>$objDate,
);
// LOOP THROUGH THE ARRAY OF DATA THAT YOU HAVE
// NOTICE THE &$data IN THE LOOP CONSTRUCT...
// THIS IS NECESSARY FOR REFERENCING WHEN WE UNSET VARIABLES WITHIN THE LOOP
foreach($arrData as $key=>&$data){
// SINCE THE XXX KEY IS STORED IN THE 'recipients' ARRAY,
// WE CHECK IF THE CURRENT KEY IS 'recipients' & THAT $data IS AN ARRAY
if($key == "recipients" && is_array($data)){
// NOW WE LOOP THROUGH THE DATA WHEREIN THE 'XXX' KEY LIVES
foreach($data as $obj){
// IF THE VALUE OF THE XXX KEY IS NULL OR NOT SET,
// WE SIMPLY UNSET IT...
if(!$obj->XXX){
unset($obj->XXX);
}
}
}
}
var_dump($arrData);
You can verify the Results HERE.
Hope this could offer you a little tip on how to implement it rightly on your own...
This should do the job
foreach($arrayOfObjects as $index => $object){
if(!isset($object->xxx) || empty($object->xxx)){
unset($arrayOfObjects[$index]);
}
}
I have seen many questions on StackOverflow and I have this code
use Zend\Session\Container;
class IndexController extends AbstractActionController {
public function indexAction() {
$userSession = new Container('user');
$userSession->username = 'Sandhya';
return new ViewModel();
}
}
When I am printing the $userSession container in the controller it is giving me this output
Zend\Session\Container Object (
[name:protected] => user
[manager:protected] => Zend\Session\SessionManager Object (
[defaultDestroyOptions:protected] => Array (
[send_expire_cookie] => 1
[clear_storage] =>
)
[name:protected] =>
[validatorChain:protected] =>
[config:protected] => Zend\Session\Config\SessionConfig Object (
[phpErrorCode:protected] =>
[phpErrorMessage:protected] =>
[rememberMeSeconds:protected] => 240
[serializeHandler:protected] =>
[validCacheLimiters:protected] => Array (
[0] => nocache
[1] => public
[2] => private
[3] => private_no_expire
)
[validHashBitsPerCharacters:protected] => Array (
[0] => 4
[1] => 5
[2] => 6
)
[validHashFunctions:protected] =>
[name:protected] =>
[savePath:protected] =>
[cookieLifetime:protected] => 2592000
[cookiePath:protected] =>
[cookieDomain:protected] =>
[cookieSecure:protected] =>
[cookieHttpOnly:protected] => 1
[useCookies:protected] => 1
[options:protected] => Array (
[gc_maxlifetime] => 2592000
)
)
[defaultConfigClass:protected] => Zend\Session\Config\SessionConfig
[storage:protected] => Zend\Session\Storage\SessionArrayStorage Object (
)
[defaultStorageClass:protected] => Zend\Session\Storage\SessionArrayStorage
[saveHandler:protected] =>
)
[storage:protected] => Array ( )
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => name
[1] => manager
[2] => storage
[3] => flag
[4] => iteratorClass
[5] => protectedProperties
)
)
It means there is nothing like username...
But when I am printing the S_SESSION it gives me this output...
Array (
[__ZF] => Array (
[_REQUEST_ACCESS_TIME] => 1429081041.81
)
[user] => Zend\Stdlib\ArrayObject Object (
[storage:protected] => Array (
[username] => Sandhya
)
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => storage
[1] => flag
[2] => iteratorClass
[3] => protectedProperties
)
)
)
There is a field username...
But when I am trying to get the $_SESSION in view it gives me the same output as above..
The problem is I am not able to get the username in both the container as well as in $_SESSION.
I need it in the controllers.
what can be the problem need help? Thank you.
I think you have to work on your configuration.
You have to setup a common SessionManager to manage handling of your session information.
Something like this:
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->start();
Container::setDefaultManager($sessionManager);
I would suggest registering your SessionManager config in your ServiceManager instance and then use it throughout the application.
'service_manager' => array(
'factories' => array(
'session_manager' => 'My\Factory\SessionManagerFactory'
)
)
You can then get your SessionManager in any controller:
$sessionManager = $this->serviceLocator->get('session_manager');
And if you create a new Container it will use your common/default SessionManager instance automatically so all will be managed in one place.
$userSession = new Container('user');
$userSession->getManager() === $this->serviceLocator->get('session_manager') // true
On how to register your session_manager I will refer to the official ZF2 documentation.
You can use the following code:
$userSession = new Container('user');
//To check the session variable in zf2:
if($userSession->offsetExists('username')){
//Your logic after check condition
}
This will return true or false on the basis of session exist or not.
//To get the value of session:
echo $user->offsetGet('username');
Above code will return the value of session index username.
Instead of $userSession->username = 'Sandhya'; you can use below code:
$user->offsetSet('username','Sandhya');
This is zf2 standard, which is used by session container in zf2.
you can just get your username from session in controllers.
$userSession = new Container('user');
$username = $userSession->username ;
var_dump($username); //Sandhya
it work for me . try it !
Good evening,
I found myself in a bit of a pickle here, with an overcomplicated (i think) $_SESSION array that is set right after a user logs in and contains the info of all User Groups where that user is on, and also this user type of permissions on Group of Devices where that specific user group is allowed.
Here's the deal with irrelevant info ommited:
Array
(
... other stuff ...
[user_groups] => Array
(
[0] => Array
(
[GroupUsersId] => 4
[GroupUsersName] => XXXX
[idUserType] => 2
[NameTypeUser] => Manager
[DevicesAllowed] => Array
(
[GroupDevicesId] => Array
(
[0] => 2
)
[DevicesOnGroup] => Array
(
[0] => 22,24,16
)
)
)
[1] => Array
(
[GroupUsersId] => 5
[GroupUsersName] => YYYY
[idUserType] => 3
[NameTypeUser] => Guest
[DevicesAllowed] => Array
(
)
)
[2] => Array
(
[GroupUsersId] => 1
[GroupUsersName] => ZZZ
[idUserType] => 1
[NameTypeUser] => Admin
[DevicesAllowed] => Array
(
[GroupDevicesId] => Array
(
[0] => 2
)
[DevicesOnGroup] => Array
(
[0] => 1,5,13,12,17,21,22,24,16
)
)
)
)
... more stuff ...
I need to find out what kind of permissions, if any, does the guy has if trying to browse the device with, let's say, DeviceId = 5. If that particular Id is not on any of the arrays, the user isn't even allowed to see it...
I already tryed to change the code in this question How to search by key=>value in a multidimensional array in PHP, but I guess I'm missing some kind of iteration over the arrays.
Any help?
Cheers and thanks in advance.
Edit: $_SESSION can be changed if needed...
(Updated as per comment below) I might be completely missing your point, but would not just iterative processing of your array help?
$user_groups = array(
0 => array(
'GroupUsersName' => 'XXX',
'NameTypeUser' => 'Admin',
'idUserType' => 3,
'DevicesAllowed' => array(
'DevicesOnGroup' => array(
1, 2, 3
)
)
),
1 => array(
'GroupUsersName' => 'YYY',
'NameTypeUser' => 'ReadOnly',
'idUserType' => 1,
'DevicesAllowed' => array(
'DevicesOnGroup' => array(
3, 4, 5
)
)
)
);
$device = 3;
$right = 0;
foreach ($user_groups as $group) {
if (array_key_exists('DevicesOnGroup', $group['DevicesAllowed'])) {
if (in_array($device, $group['DevicesAllowed']['DevicesOnGroup'])) {
if ($group['idUserType'] > $right) {
$right = $group['idUserType'];
}
}
}
}
print_r($right);
Outputs:
3
If you would ask for device which is in no group, it would return 0 (i.e. no access).
iterate the array like this
$guysDeviceId ;
$bGuyMayPass = false;
foreach($_SESSION["user_group"] as $userGroup ){
if(!isset($userGroup[DevicesAllowed]) || !isset($userGroup[DevicesAllowed][DevicesOnGroup])){
continue;
}
if(in_array($userGroup[DevicesAllowed][DevicesOnGroup], $guysDeviceId ){
$bGuyMayPass= true;
}
}
if($bGuyMayPass){
//login, whatever
}
I'm looking for a way to make it so cake returns all database data in the same format/structure... Currently it returns two different types of format depending on the relationship.
If a model 'B' is associated with the current model 'A' being queried it will then place model associations for 'B' underneath it as you can see in [User] below. I want it so that all queries use that structure.
example:
$this->find('all', ....
returns:
Array
(
[0] => Array
(
[UserGroup] => Array
(
[id] => 53
[user_id] => 100003332014851
[media_id] =>
[name] => john
[description] => qwasdfad
)
[User] => Array
(
[id] => 100003332014851
[session_id] => ssm2qbrotmm13ho1ipm8ii2492
[username] =>
[password] => -1
[Planner] => Array
(
)
[Purchase] => Array
(
)
[Listing] => Array
(
)
)
)
I want this to look like:
Array
(
[0] => Array
(
[UserGroup] => Array
(
[id] => 53
[user_id] => 100003332014851
[media_id] =>
[name] => john
[description] => qwasdfad
[User] => Array
(
[id] => 100003332014851
[session_id] => ssm2qbrotmm13ho1ipm8ii2492
[username] =>
[password] => -1
[Planner] => Array
(
)
[Purchase] => Array
(
)
[Listing] => Array
(
)
)
)
)
)
In CakePHP, the find() method return data like your first format. But If you want to format like second one then you have to process it by hand (try to avoid this if possible)
$data = $this->find('all');
$assocs = Set::extract('/User', $data); // extracting all `User` array
foreach($assocs as $key => $assoc) {
unset($data[$key]['User']); // removing the associate `User` from `$data`
$data[$key]['UserGroup']['User'] = $assoc['User']; // adding associate under `UserGroup`
}
ended up doing this... it changes the output to what we need. The top level item does not have a header which is fine I just adjusted our scripts for that... maybe this will help somebody else if they need a custom idea
also no guarantee this covers all possible results but so far it works with all the queries we have.
class AppModel extends Model {
function afterFind($results, $primary) {
//if this is a primary, structure like a secondary so entire site is same format
if ($primary) {
$class = get_class($this);
//simple fix for primary
foreach ($results as $key => $result) {
$result = $this->formatData($result, $class);
$results[$key] = $result;
}
}
return $results;
}
function formatData($result, $class) {
$array = array();
if (isset($result[$class])) {
$array = $result[$class];
unset($result[$class]);
}
$array += $result;
return $array;
}
You can also use contain in this case along with find as UserGroup.User for your desired result