How to use Zend\Session in zf2? - php

Does anybody try zf2? I can not understand new mechanism of using sessions in zf2. How can I write and read to/from the session in new zend framework?
Also I can not find any examples in the internet.

Some examples of zf2 sessions usage:
Session creation:
use Zend\Session\Container;
$session = new Container('base');
Check that key exists in session:
$session->offsetExists('email')
Getting value from the session by key:
$email = $session->offsetGet('email');
Setting value in session:
$session->offsetSet('email', $email);
Unsetting value in session:
$session->offsetUnset('email');
And other easy way to use session are:
$session = new Container('foo');
// these are all equivalent means to the same end
$session['bar'] = 'foobar';
$session->bar = 'foobar';
$session->offsetSet('bar', 'foobar');

Definitely yes, you should use Zend\Session\Container
Container extends of ArrayObject and instantiates with ARRAY_AS_PROPS flag that means you can easily iterate through properties and read/write them, e.g.
use Zend\Session\Container as SessionContainer;
$this->session = new SessionContainer('post_supply');
$this->session->ex = true;
var_dump($this->session->ex);
First argument is session namespace and second — Manager. Manager is a facade for Storage and SaveHandler and it's configured with ConfigInterface in order to save your session data in DB or Memcache server.

I'm currently working with zf2. I found usage of Sessions in:
Zend\Authentication\Storage\Session.php
Maybe you can find your answer there.

If you are trying to use session in your login action, you can use: "Zend\Authentication\AuthenticationService". It Authenticates the user and store session as well.
getStorage()->write($contents) will store the session.

well here is the brief example. i have implemented regarding maintaining session on successful authentication of user.
<?php
$registry = Zend_Registry::getInstance();
$DB = $registry['DB'];
$authAdapter = new Zend_Auth_Adapter_DbTable($DB);
$authAdapter->setTableName('user');
$authAdapter->setIdentityColumn("user_name");
$authAdapter->setCredentialColumn("user_password");
//get values
$username = $request->getParam('username');
$password = $request->getParam('password');
//set values
$authAdapter->setIdentity($username);
$authAdapter->setCredential($password);
$auth = Zend_Auth::getInstance();
//to store in session
$auth->setStorage(new Zend_Auth_Storage_Session('front'));
$authResult = $auth->authenticate($authAdapter);
if ($authResult->isValid()) {
$authAdap = $authAdapter->getResultRowObject(null, "Password");
$auth->getStorage()->write($authAdap);
$this->_redirect('/login/controlpannel');
} else {
$this->_redirect('/login/login');
}
?>
getting values or check data stored in session related to user
<?php
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('front'));
if($auth->hasIdentity()){
$data = $auth->getStorage()->read();
print_r($data);
}else{
$this->_redirect('/login/login');
}
?>
hope this could help someone

use Zend\Session\Container;
public function createAction(){
$session = new Container('name');
$session->offsetSet('session_variable', $value);
}
//the above codes are used for create session.
public function take_valuesAction(){
$session = new Container('name');
echo $value = $session->offsetGet('session_variable');
}
//the above codes are used for take values from session.
public function destroyAction(){
$session = new Container('name');
$session->getManager()->destroy();
}
//the above codes are used for destroy the session.

To start a session you need to use
zend\session\container

Related

Use session variable as object in PHP

Need some assistance. I am getting the following errors
Fatal error: Call to a member function getName() on string in......
This refers to the line on by index.php
$session->getName()
The code.
index.php
include 'classes/user.php';
$session = isset($_SESSION['userObj']) ? $_SESSION['userObj'] : "";
include 'login.php';
$session->getName()
login.php
session_start();
$user = new User();
$user->setAll($db_id,$db_fullname,$db_username,$db_rights, $db_last_login,$db);
$_SESSION['userObj'] = $user;
How do you pass objects correctly via session vars? I've checked on this site and its advised to do it like i have.
I know i'm not doing the else statement right on the isset part. Should i be doing.
else{ $session = new User();}
Use serialize()
//Set object as session
$user = new User();
$_SESSION['userObj'] = serialize($user);
//Get object
$user = unserialize($_SESSION['userObj']);
FYI, don't forget to write session_start(); on first line of every page to use $_SESSION.

session fixation in Joomla 2.5

Impact that this can cause: It is possible to steal or manipulate customer session and cookies, which might be used to impersonate a legitimate user, allowing the hacker to view or alter user records, and to perform transactions as that user.
And recommended solution to prevent session fixation attacks is to renew the session ID when a user logs in. This fix can be done at the code level or framework level, depending on where the session management functionality is implemented.
I'm trying to find a fix for this and still i'm not successful. Anyone can help how to fix this in Joomla 2.5?
I want to implement this fix at framework level. Any help will be appreciated.
I did this for Joomla 3.x version. It should be similar in 2.5.
You should modify 2 files to make this work.
libraries/cms/application/cms.php
libraries/joomla/session/session.php
in cms.php modify the function login
// Import the user plugin group.
JPluginHelper::importPlugin('user');
if ($response->status === JAuthentication::STATUS_SUCCESS)
{
$session = &JFactory::getSession();
// we fork the session to prevent session fixation issues
$session->fork();
/*
* Validate that the user should be able to login (different to being authenticated).
* This permits authentication plugins blocking the user.
*/
$authorisations = $authenticate->authorise($response, $options);
in session.php change the function fork() to include
function fork()
{
if( $this->_state !== 'active' ) {
// #TODO :: generated error here
return false;
}
// save values
$values = $_SESSION;
// keep session config
/*$trans = ini_get( 'session.use_trans_sid' );
if( $trans ) {
ini_set( 'session.use_trans_sid', 0 );
} */
$cookie = session_get_cookie_params();
// create new session id
//$id = $this->_createId( strlen( $this->getId() ) );
session_regenerate_id(true);
$id = session_id();
// first we grab the session data
$data = $this->_store->read($this->getId());
// kill session
session_destroy();
// re-register the session store after a session has been destroyed, to avoid PHP bug
$this->_store->register();
// restore config
ini_set( 'session.use_trans_sid', $trans );
session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure'], true);
// restart session with new id
session_id( $id );
//session_regenerate_id(true);
session_start();
$_SESSION = $values;
//now we put the session data back
$this->_store->write($id, $data);
return true;
}
Thanks a lot #ryadavalli ! It is very helpful. Using your suggested solution, I solved it for Joomla 2.5.
Only few changes; for Joomla 2.5 the code needs to be placed in
libraries/joomla/application/application.php
libraries/joomla/session/session.php
In application.php w.r.t your solution
public function login($credentials, $options = array())
{
// Get the global JAuthentication object.
jimport('joomla.user.authentication');
$authenticate = JAuthentication::getInstance();
$response = $authenticate->authenticate($credentials, $options);
// Import the user plugin group.
JPluginHelper::importPlugin('user');
if ($response->status === JAuthentication::STATUS_SUCCESS)
{
$session = &JFactory::getSession();
// we fork the session to prevent session fixation issues
$session->fork();
// validate that the user should be able to login (different to being authenticated)
// this permits authentication plugins blocking the user
$authorisations = $authenticate->authorise($response, $options);
In session.php, updated the code as following
public function fork()
{
if ($this->_state !== 'active')
{
// #TODO :: generated error here
return false;
}
// Save values
$values = $_SESSION;
// Keep session config
/*$trans = ini_get('session.use_trans_sid');
if ($trans)
{
ini_set('session.use_trans_sid', 0);
} */
$cookie = session_get_cookie_params();
// Create new session id
//$id = $this->_createId();
session_regenerate_id(true);
$id = session_id();
// first we grab the session data
$data = $this->_store->read();
// Kill session
session_destroy();
// Re-register the session store after a session has been destroyed, to avoid PHP bug
$this->_store->register();
// Restore config
ini_set('session.use_trans_sid', $trans);
session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure']);
// Restart session with new id
session_id($id);
session_start();
$_SESSION = $values;
//now we put the session data back
$this->_store->write($id, $data);
return true;
}

Why Session details are not accessible inside php namespace

I have developing a basic session handler class. The issue is when ever I am setting session into any controller action, same session details are not accessible in other action/controller. It displays me empty array. Entire system is php namespace oriented.
Reference: Session Manager
We do save and retrieve session as below.
use Cygnite\Common\SessionManager\Session;
use Cygnite\Common\Encrypt;
$session = new Session(new Encrypt);
$session->save($key, $value);
$userDetails = $session->get($key);
var_dump($userDetails);
It works inside the same action and but when ever I am redirecting into some other controller ->action session doesn't display anything.
Can anyone help?
Probably you create in each controller new Session object. And it's quite possible you should create one Session object and inject it for example as constructor argument to other classes.
use Cygnite\Common\SessionManager\Session;
use Cygnite\Common\Encrypt;
$session = new Session(new Encrypt);
$session->save('something', 'My data');
class A
{
private $session;
public function __construct($session) {
$this->session = $session;
echo $this->sesssion->get('something'); // it should work
$x = new Session(new Encrypt);
echo $x->get('something'); // possible it won't work
}

Change Session ID And Keep Data in PHP Zend

I want to change the session id once the user has logged in to a custom random session id with my own prefix.
However, when I do the below the session data is lost;
Zend_Session:setId('my-new-id');
Zend_Session:start();
But if I do the following the session data will still be available;
Zend_Session:regenerateId();
Zend_Session:start();
Anyidea how can I fix this issue?
see in library/Zend/Session.php:316:
if ( !self::$_sessionStarted ) {
self::$_regenerateIdState = -1;
} else {
if (!self::$_unitTestEnabled) {
session_regenerate_id(true);
}
self::$_regenerateIdState = 1;
}
Best practice is to call this after session is started. If called prior to session starting, session id will be regenerated at start time.
also see: Global Session Management with ZF1:
$defaultNamespace = new Zend_Session_Namespace();
if (!isset($defaultNamespace->initialized)) {
Zend_Session::regenerateId();
$defaultNamespace->initialized = true;
}
added:
Then try this:
$commit = Zend_Session::namespaceGet('Default');
Zend_Session::writeClose(false);
// ^ session_commit(); // see Advanced Usage: http://framework.zend.com/manual/1.12/en/zend.session.advanced_usage.html#zend.session.advanced_usage.starting_a_session
.. change id with session_id("my-new-id");
// start new session ...
$namespace = new Zend_Session_Namespace('Default');
foreach($commit as $idx => $data){
$namespace->$idx = $data;
}
However! after calling Zend_Session::writeClose() we cannot restart session with Zend_Session::start() version of 22744dd
see this issue:
https://github.com/zendframework/zf1/issues/159
fixed version: https://github.com/itscaro/zf1/blob/bbebe445d8551582cba6f5e9c9c1a8396fb2b322/library/Zend/Session.php#L436
anyway, I recommend watching the documentation of the start session - Starting a Session
and/or use Zend_Session::regenerateId(); instead of Zend_Session::setId()

Setting Sessions inside PHP Class

I'm creating a user class to handle my logins. As I wish to set the sessions inside the class after the username and password are validated, do I have to use session_start() at the top of the class, inside the public function where the sessions are to be set, or where the instance is created? Perhaps it could go inside function _construct()?
This is how I would like to call the class:
<php
include('user_class.php');
$user = new user;
$user->login($username,$password);
?>
You can just add session_start(); at the top of the file you're including the class in.
So
<?php
session_start();
include('user_class.php');
$user = new user;
$user->login($username,$password);
?>
would work.
Next to your user-class create yourself a session-class as well.
The user-class then is just storing itself into the session class and does not need to take care about calling session_start or not, that's the job of the session-class.
<php
include('session_class.php');
include('user_class.php');
$session = new session;
if ($session->hasRegisteredUser()) {
$user = $session->getRegisteredUser();
} else {
$user = new user;
    $user->login($username, $password);
$session->setRegisteredUser($user);
}
Does this answer your question or do you need now to know how to do it with the session class?
Yes you can use sessions inside your classes because sessions are global variables in php.
Code Example(adding a new session variable):
<?php
class sessionControle{
...
...
public function addSession($index, $value){
$_SESSION[$index] = $value;
return $_SESSION[$index];
}
}
?>
in your main php file you can include the function $_SESSIONS are global
Code in your main file:
<?php
session_start();
include_once("myClass.php");
$Se = new sessionControle;
echo $Se->addSession('User', 'Crx');
//Double check here !!
echo $_SESSION['User'];
?>
Output: Crx

Categories