According to CodeIgniter documentation their Shopping Cart Class "is DEPRECATED and should not be used".
Is there any harm in going ahead and using it? It is a very close match to what I need and I cannot see a similar library anywhere else.
using codeigniter cart class is fine as long as the session class is secure, but ci 2.x session is not secure since it saves its data in a cookie "ci_session" so the end user can modify session data (including cart data)
to overcome this vulnerability you can use a session extension that doesn't save any session data in the browser cookie, you can use something like EckoTools Session Library , that you put in your libraries/session.php and use it as you use ci native session , and here is the library code :
note: this library assumes that you are using the database to save session data , so you should enable this $config['sess_use_database'] = TRUE; in your config.php file
<?php
/**
The EckoTools Session Library
#package The EckoTools Session Library
#category Libraries
#author Hartmut König (h.koenig#eckotools.com)
#link http://www.okidoe.de
#version 1.0.2
#copyright Hartmut König 2009
A class to handle sessions by using a mySQL database for session related
data storage providing better security then the default session handler
used by PHP with added protection against Session Hijacking & Fixation
including the flashdata-Feature of CI. It don't use Browser or IP to identify
the user. Instead I generate a fingerprint of different seldom changing data
(#link _generate_fingerprint)
To prevent session hijacking, don't forget to use the {#link regenerate_id}
method whenever you do a privilege change in your application
--
-- MYSQL: Table structure for table `ci_sessions`
--
CREATE TABLE `ci_sessions` (
`session_id` varchar(32) NOT NULL default '',
`fingerprint` varchar(32) NOT NULL default '',
`session_data` blob NOT NULL,
`session_expire` int(11) NOT NULL default '0',
PRIMARY KEY (`session_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
This class is an adaptation between the original CI Sessions, Native Sessions
and my own coding
*/
error_reporting(E_ALL);
class CI_Session
{
/**
* Constructor of class
*
* Initializes the class and starts a new session
*
* There is no need to call start_session() after instantiating this class
*
* $gc_maxlifetime (optional) the number of seconds after which data will be seen as 'garbage' and
* cleaned up on the next run of the gc (garbage collection) routine
*
* Default is specified in php.ini file
*
* $gc_probability (optional) used in conjunction with gc_divisor, is used to manage probability that
* the gc routine is started. the probability is expressed by the formula
*
* probability = $gc_probability / $gc_divisor
*
* So if $gc_probability is 1 and $gc_divisor is 100 means that there is
* a 1% chance the the gc routine will be called on each request
*
* Default is specified in php.ini file
*
* $gc_divisor (optional) used in conjunction with gc_probability, is used to manage probability
* that the gc routine is started. the probability is expressed by the formula
*
* probability = $gc_probability / $gc_divisor
*
* So if $gc_probability is 1 and $gc_divisor is 100 means that there is
* a 1% chance the the gc routine will be called on each request
*
* Default is specified in php.ini file
*
* $security_code (optional) the value of this argument is appended to the fingerprint before
* creating the md5 hash out of it. this way we'll try to prevent fingerprint
* spoofing
*
* Default is 'LeouOeEkKpvSnD-YCHd5ogt3y'
*
* $table_name (optional) You can change the name of that table by setting this property
*
* Default is 'ci_sessions'
*
* #return void
*/
function CI_Session( $security_code="LeouOeEkKpvSnD-YCHd5ogt3y",$table_name="ci_sessions" )
{
//-- CI Config
$this->CI = & get_instance();
$this->flashdata_key = 'flash'; // prefix for "flash" variables (eg. flash:new:message)
$table_name = $this->CI->config->item('sess_table_name');
$gc_maxlifetime = $this->CI->config->item('sess_expiration');
$gc_probability = $this->CI->config->item('sess_gc_probability');
$gc_divisor = $this->CI->config->item('sess_gc_divisor');
$sess_name = $this->CI->config->item('sess_cookie_name');
// if $gc_maxlifetime is specified and is an integer number
(!empty($gc_maxlifetime) && is_integer($gc_maxlifetime))
? #ini_set('session.gc_maxlifetime', $gc_maxlifetime)
: false;
// if $gc_probability is specified and is an integer number
(!empty($gc_probability) && is_integer($gc_probability))
? #ini_set('session.gc_probability', $gc_probability)
: false;
// if $gc_divisor is specified and is an integer number
(!empty($gc_divisor) && is_integer($gc_divisor))
? #ini_set('session.gc_divisor', $gc_divisor)
: false;
(!empty($sess_name))
? #ini_set('session.name', $sess_name)
: false;
// get session lifetime
$this->sessionLifetime = ini_get("session.gc_maxlifetime");
// we'll use this later in order to prevent fingerprint spoofing
$this->securityCode = $security_code;
$this->tableName = $table_name;
// register the new handler
session_set_save_handler(
array(&$this, '_open'),
array(&$this, '_close'),
array(&$this, '_read'),
array(&$this, '_write'),
array(&$this, '_destroy'),
array(&$this, '_gc')
);
register_shutdown_function('session_write_close');
// start the session
session_start();
// Delete 'old' flashdata (from last request)
$this->_flashdata_sweep();
// Mark all new flashdata as old (data will be deleted before next request)
$this->_flashdata_mark();
}
/**
* Reads given session attribute value
*
* #return integer sessionvalue
*/
function userdata($item)
{
//added for backward-compatibility
if($item == 'session_id')
{
return session_id();
}
if(isset($_SESSION[$item]))
{
return($_SESSION[$item]);
}
return(false);
}
/**
* Fetch all session data
*
* #access public
* #return mixed
*/
function all_userdata()
{
return ( ! isset($_SESSION)) ? FALSE : $_SESSION;
}
/**
* Sets session attributes to the given values
*
* #return void
*/
function set_userdata($newdata = array(), $newval = '')
{
(is_string($newdata))
? $newdata = array($newdata => $newval)
: false;
if(count($newdata) > 0)
{
foreach($newdata as $key => $val)
{
$_SESSION[$key] = $val;
}
}
}
/**
* Erases given session attributes
*
* #return void
*/
function unset_userdata($newdata = array())
{
(is_string($newdata))
? $newdata = array($newdata => '')
: false;
if(count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
unset($_SESSION[$key]);
}
}
}
/**
* Deletes all data related to the session
* #return void
*/
function sess_destroy()
{
$this->regenerate_id();
session_unset();
session_destroy();
}
/**
* Regenerates the session id.
*
* <b>Call this method whenever you do a privilege change!</b>
*
* #return void
*/
function regenerate_id()
{
// saves the old session's id
$oldSessionID = session_id();
// regenerates the id
// this function will create a new session, with a new id and containing the data from the old session
// but will not delete the old session
session_regenerate_id();
// because the session_regenerate_id() function does not delete the old session,
// we have to delete it manually
$this->_destroy($oldSessionID);
}
/**
* Add or change flashdata, only available
* until the next request
*
* #access public
* #param mixed
* #param string
* #return void
*/
function set_flashdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$flashdata_key = $this->flashdata_key.':new:'.$key;
$this->set_userdata($flashdata_key, $val);
}
}
}
// ------------------------------------------------------------------------
/**
* Keeps existing flashdata available to next request.
*
* #access public
* #param string
* #return void
*/
function keep_flashdata($key)
{
// 'old' flashdata gets removed. Here we mark all
// flashdata as 'new' to preserve it from _flashdata_sweep()
// Note the function will return FALSE if the $key
// provided cannot be found
$old_flashdata_key = $this->flashdata_key.':old:'.$key;
$value = $this->userdata($old_flashdata_key);
$new_flashdata_key = $this->flashdata_key.':new:'.$key;
$this->set_userdata($new_flashdata_key, $value);
}
// ------------------------------------------------------------------------
/**
* Fetch a specific flashdata item from the session array
*
* #access public
* #param string
* #return string
*/
function flashdata($key)
{
$flashdata_key = $this->flashdata_key.':old:'.$key;
return $this->userdata($flashdata_key);
}
// ------------------------------------------------------------------------
/**
* Identifies flashdata as 'old' for removal
* when _flashdata_sweep() runs.
*
* #access private
* #return void
*/
function _flashdata_mark()
{
$userdata = $this->all_userdata();
foreach ($userdata as $name => $value)
{
$parts = explode(':new:', $name);
if (is_array($parts) && count($parts) === 2)
{
$new_name = $this->flashdata_key.':old:'.$parts[1];
$this->set_userdata($new_name, $value);
$this->unset_userdata($name);
}
}
}
// ------------------------------------------------------------------------
/**
* Removes all flashdata marked as 'old'
*
* #access private
* #return void
*/
function _flashdata_sweep()
{
$userdata = $this->all_userdata();
foreach($userdata as $key => $value)
{
if (strpos($key, ':old:'))
{
$this->unset_userdata($key);
}
}
}
/**
* Get the number of online users
*
* #return integer number of users currently online
*/
function get_users_online()
{
// counts the rows from the database
$query = $this->CI->db->query("SELECT COUNT(session_id) as count FROM ".$this->tableName);
$result = $query->row();
// return the number of found rows
return $result->count;
}
/**
* Generates key as protection against Session Hijacking & Fixation.
* #access private
* #return string
*/
function _generate_fingerprint()
{
//-- We don't use the ip-adress, because this is a subject to change in most cases (proxies etc.)
$list = array('HTTP_ACCEPT_CHARSET',
'HTTP_ACCEPT_ENCODING',
'HTTP_ACCEPT_LANGUAGE',
'HTTP_USER_AGENT');
$key = array($this->securityCode);
foreach($list as $item)
{
$key[] = $this->CI->input->server($item);
}
return md5(implode("\0", $key));
}
/**
* Custom open() function
*
* #access private
*/
function _open($save_path, $session_name)
{
return(true);
}
/**
* Custom close() function
*
* #access private
*/
function _close()
{
return(true);
}
/**
* Custom read() function
*
* #access private
*/
function _read($session_id)
{
// reads session data associated with the session id
// but only
// - if the fingerprint is the same as the one who had previously written to this session AND
// - if session has not expired
$result = $this->CI->db->query("SELECT session_data ".
"FROM ".$this->tableName." ".
"WHERE session_id = ".$this->CI->db->escape($session_id)." ".
"AND fingerprint = ".$this->CI->db->escape($this->_generate_fingerprint())." ".
"AND session_expire > '".time()."' LIMIT 1");
// if anything was found
if($result->num_rows() > 0)
{
// return found data
$fields = $result->row();
// Unserialization - PHP handles this automatically
return $fields->session_data;
}
// if there was an error return an empty string - this HAS to be an empty string
return("");
}
/**
* Custom write() function
*
* #access private
*/
function _write($session_id, $session_data)
{
// insert OR update session's data - this is how it works:
// first it tries to insert a new row in the database BUT if session_id is already in the database then just
// update session_data and session_expire for that specific session_id
// read more here http://dev.mysql.com/doc/refman/4.1/en/insert-on-duplicate.html
$result = $this->CI->db->query(
"INSERT INTO ".$this->tableName." (".
"session_id,".
"fingerprint,".
"session_data,".
"session_expire".
") VALUES (".
$this->CI->db->escape($session_id).",".
$this->CI->db->escape($this->_generate_fingerprint()).",".
$this->CI->db->escape($session_data).",".
$this->CI->db->escape(time() + $this->sessionLifetime).
")".
"ON DUPLICATE KEY UPDATE ".
"session_data = ".$this->CI->db->escape($session_data).",".
"session_expire = ".$this->CI->db->escape(time() + $this->sessionLifetime));
// note that after this type of queries, mysql_affected_rows() returns
// - 1 if the row was inserted
// - 2 if the row was updated
switch($this->CI->db->affected_rows())
{
// if the row was inserted
case 1:
return("");
break;
// if the row was updated
case 2:
return(true);
break;
// if something went wrong, return false
default:
return(false);
break;
}
}
/**
* Custom destroy() function
*
* #access private
*/
function _destroy($session_id)
{
// deletes the current session id from the database
$result = $this->CI->db->query("DELETE FROM ".$this->tableName." ".
"WHERE session_id = ".$this->CI->db->escape($session_id));
// if anything happened
if($this->CI->db->affected_rows())
{
return(true);
}
// if something went wrong, return false
return(false);
}
/**
* Custom gc() function (garbage collector)
*
* #access private
*/
function _gc($maxlifetime)
{
// it deletes expired sessions from database
$result = $this->CI->db->query("DELETE FROM ".$this->tableName." ".
"WHERE session_expire < ".$this->CI->db->escape(time() - $maxlifetime));
}
}
?>
cheers!
3 years after, a better solution, out of the box.
I've found this on MIT license: https://github.com/kirilkirkov/Shopping-Cart-Solution-CodeIgniter
Using CI3, not using CI cart class, back-end, templates, payments, languages etc. Excellent work!
Related
I just try to create my first extension about flowers with a list view and and a detail view. Now I want to add the possibility to browse through the flowers on detail view.
I found the following code Extbase Repository: findNext und findPrevious Funktionen
and added it to my repository
/**
* The repository for Pflanzens
*/
class PflanzenRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
protected $defaultOrderings = array(
'nameDeutsch' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
);
/**
* Find next item by uid
* #param integer $uid The uid of the current record
* #return boolean|\TYPO3\CMS\Extbase\Persistence\Generic\QueryResult
*/
public function findNext($uid) {
$query = $this->createQuery();
$result = $query->matching($query->greaterThan('uid',$uid))->setLimit(1)->execute();
if($query->count()) {
return $result;
} else {
return false;
}
}
/**
* Find previous item by uid
* #param integer $uid The uid of the current record
* #return boolean|\TYPO3\CMS\Extbase\Persistence\Generic\QueryResult
*/
public function findPrev($uid) {
$query = $this->createQuery();
$ordering = array('uid'=>\TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING);
$result = $query->matching($query->lessThan('uid',$uid))->setLimit(1)->setOrderings($ordering)->execute();
if($query->count()) {
return $result;
} else {
return false;
}
}
}
This is my controller right now:
/**
* PflanzenController
*/
class PflanzenController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
/**
* pflanzenRepository
*
* #var \TMRuebe\Faerbepflanzen\Domain\Repository\PflanzenRepository
* #inject
*/
protected $pflanzenRepository = NULL;
/**
* action list
*
* #return void
*/
public function listAction()
{
$pflanzens = $this->pflanzenRepository->findAll();
$this->view->assign('pflanzens', $pflanzens);
}
/**
* action show
*
* #param \TMRuebe\Faerbepflanzen\Domain\Model\Pflanzen $pflanzen
* #return void
*/
public function showAction(\TMRuebe\Faerbepflanzen\Domain\Model\Pflanzen $pflanzen)
{
$this->view->assign('pflanzen', $pflanzen);
}
}
Now I need help how to add the two public functions to the controller. And I also need a hint for the variable that I can use in my fluid template to create the previous link and the next link.
in showAction() you need to assign to further variables with the results of findNext() and findPrev().
$this->view->assign('previous', \TMRuebe\Faerbepflanzen\Domain\Repository\PflanzenRepository::findPrev($pflanzen['uid']));
$this->view->assign('next', \TMRuebe\Faerbepflanzen\Domain\Repository\PflanzenRepository::findNext($pflanzen['uid']));
in your detail template you need to build the links like the links in the list view.
You might build methods using the current object to get easier access to next and prev.
I am using magento version 1.9.0.1.
For switching to magento purposes I need to create a login function for customers outside the magento framework.
I have looked up the method magento uses to hash and validate passwords, but the method doesn't seem to work anymore.
Below the code I use to validate a user login outside magento. This code is just to try proof of concept and is not being used in a live environment for obvious reasons :).
function checkPassword($entity,$passwordInput){
$query = mysql_query("SELECT value FROM customer_entity_varchar WHERE entity_id = '$entity' AND attribute_id = '12' LIMIT 1");
$fetch = mysql_fetch_object($query);
$fetch_data = explode(':',$fetch->value);
$hashed_password = $fetch_data['0'];
$salt = $fetch_data['1'];
$hashInput = md5($passwordInput . $salt);
if($hashInput == $hashed_password){
return 'Success';
}
else{
return 'Failure';
}
}
$entity is the entity_id passed after email validation,
$passwordInput is the password entered in the login form.
It returns Failure. Which I'm not surprised about because when I return $hashInput and compare it with $hashed_password it's not the same.
Has the way Magento hashes passwords been changed? Or is there a mistake in my code?
If you check in \app\code\core\Mage\Customer\Model\Customer.php you can find something like this (near line 430) :
/**
* Encrypt password
*
* #param string $password
* #return string
*/
public function encryptPassword($password)
{
return Mage::helper('core')->encrypt($password);
}
The helper('core') is \app\code\core\Mage\Core\Helper\Data.php
In \app\code\core\Mage\Core\Helper\Data.php, you find :
/**
* Encrypt data using application key
*
* #param string $data
* #return string
*/
public function encrypt($data)
{
if (!Mage::isInstalled()) {
return $data;
}
return $this->getEncryptor()->encrypt($data);
}
and getEncryptor() function is :
/**
* #return Mage_Core_Model_Encryption
*/
public function getEncryptor()
{
if ($this->_encryptor === null) {
$encryptionModel = (string)Mage::getConfig()->getNode(self::XML_PATH_ENCRYPTION_MODEL);
if ($encryptionModel) {
$this->_encryptor = new $encryptionModel;
} else {
$this->_encryptor = Mage::getModel('core/encryption');
}
$this->_encryptor->setHelper($this);
}
return $this->_encryptor;
}
$this->_encryptor is in \app\code\core\Mage\Core\Model\Encryption.php and in this file you can find :
/**
* Encrypt a string
*
* #param string $data
* #return string
*/
public function encrypt($data)
{
return base64_encode($this->_getCrypt()->encrypt((string)$data));
}
and
/**
* Instantiate crypt model
*
* #param string $key
* #return Varien_Crypt_Mcrypt
*/
protected function _getCrypt($key = null)
{
if (!$this->_crypt) {
if (null === $key) {
$key = (string)Mage::getConfig()->getNode('global/crypt/key');
}
$this->_crypt = Varien_Crypt::factory()->init($key);
}
return $this->_crypt;
}
(string)Mage::getConfig()->getNode('global/crypt/key'); is in /app/etc/local.xml file.
Your variable $hashed_password pass by this last method.
Your variable $hashInput also pass there ?
So, you can change in your checkPassword() function :
$hashInput = md5($passwordInput . $salt);
to
$hashInput = encryptPassword($passwordInput);
Thereby, $hashInput and $hashed_password will follow the same way.
Is it possible to do caching of data from sql server queries when using CSqlDataProvider. If so can anyone please provide some links for documentation about it. Or if you have done it personally please guide.
I did a search but found nothing :(
There is some example of implementing this feature
<?php
class CachedSqlDataProvider extends CDataProvider
{
public $queryCache;
public $queryCacheLife;
/**
* #var CDbConnection the database connection to be used in the queries.
* Defaults to null, meaning using Yii::app()->db.
*/
public $db;
/**
* #var string the SQL statement to be used for fetching data rows.
*/
public $sql;
/**
* #var array parameters (name=>value) to be bound to the SQL statement.
*/
public $params=array();
/**
* #var string the name of key field. Defaults to 'id'.
*/
public $keyField='id';
/**
* Constructor.
* #param string $sql the SQL statement to be used for fetching data rows.
* #param array $config configuration (name=>value) to be applied as the initial property values of this class.
*/
public function __construct($sql,$config=array())
{
$this->sql=$sql;
foreach($config as $key=>$value)
$this->$key=$value;
}
/**
* Fetches the data from the persistent data storage.
* #return array list of data items
*/
protected function fetchData()
{
$sql=$this->sql;
$db=$this->db===null ? Yii::app()->db : $this->db;
$db->active=true;
if(($sort=$this->getSort())!==false)
{
$order=$sort->getOrderBy();
if(!empty($order))
{
if(preg_match('/\s+order\s+by\s+[\w\s,]+$/i',$sql))
$sql.=', '.$order;
else
$sql.=' ORDER BY '.$order;
}
}
if(($pagination=$this->getPagination())!==false)
{
$pagination->setItemCount($this->getTotalItemCount());
$limit=$pagination->getLimit();
$offset=$pagination->getOffset();
$sql=$db->getCommandBuilder()->applyLimit($sql,$limit,$offset);
}
if( $this->queryCache == true && $this->queryCacheLife > 0 )
$command=$db->cache( $this->queryCacheLife )->createCommand($sql);
else
$command=$db->createCommand($sql);
foreach($this->params as $name=>$value)
$command->bindValue($name,$value);
return $command->queryAll();
}
/**
* Fetches the data item keys from the persistent data storage.
* #return array list of data item keys.
*/
protected function fetchKeys()
{
$keys=array();
foreach($this->getData() as $i=>$data)
$keys[$i]=$data[$this->keyField];
return $keys;
}
/**
* Calculates the total number of data items.
* This method is invoked when {#link getTotalItemCount()} is invoked
* and {#link totalItemCount} is not set previously.
* The default implementation simply returns 0.
* You may override this method to return accurate total number of data items.
* #return integer the total number of data items.
*/
protected function calculateTotalItemCount()
{
return 0;
}
}
?>
Created a cookie using javascript
function (c_name,value,exdays) {
value = source ;
c_name = "Cookie" ;
var exdate=new Date();
exdays = exdate.setTime(exdate.getTime() + (30*24*60*60*1000));
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
});
Can i retrieve using Mage::getModel(‘core/cookie’)->get(); ??
If you would look inside the class Mage_Core_Model_Cookie the definition for the method get is:
/**
* Retrieve cookie or false if not exists
*
* #param string $neme The cookie name
* #return mixed
*/
public function get($name = null)
{
return $this->_getRequest()->getCookie($name, false);
}
The _getRequest() retreives an instance of Mage_Core_Controller_Request_Http a class that extends Zend_Controller_Request_Http inside which the method getCookie is defined as:
/**
* Retrieve a member of the $_COOKIE superglobal
*
* If no $key is passed, returns the entire $_COOKIE array.
*
* #todo How to retrieve from nested arrays
* #param string $key
* #param mixed $default Default value to use if key not found
* #return mixed Returns null if key does not exist
*/
public function getCookie($key = null, $default = null)
{
if (null === $key) {
return $_COOKIE;
}
return (isset($_COOKIE[$key])) ? $_COOKIE[$key] : $default;
}
So yes, you can retrieve a cookie using Magento classes and methods, Zend or the $_COOKIE superglobal.
Yes, you can access javascript cookies, in your case by using:
$cookieValue = Mage::getModel('core/cookie')->get('Cookie');
Also, If it doesn't require that you set the cookie via JavaScript you can set it by:
/*
* ->set('name', 'value', 'expDate', 'path', 'domain', 'secure', 'httpsOnly')
* Only Name and Value are required. expDate set for 24 hours below.
*/
Mage::getModel('core/cookie')->set('Cookie', source, time()+86400);
I am writing an extbase extension on typo3 v6.1
That extension suppose to do a bus ticket booking.
Here what my plan is, user will select date and number of seats and submit the form.
Here my plan to push the date and rate of the selected seat to session (Basket).
And while making payment, I wanted to get that values from session and after payment I need to clear that particular session.
So In short, How to Push and retrieve the values to and from the session in extbase.
Any suggestions ?
Thank you.
There are different ways. The simplest would be for writing in the session
$GLOBALS['TSFE']->fe_user->setKey("ses","key",$value)
and for reading values from the session
$GLOBALS["TSFE"]->fe_user->getKey("ses","key")
I'm using for this a service class.
<?php
class Tx_EXTNAME_Service_SessionHandler implements t3lib_Singleton {
private $prefixKey = 'tx_extname_';
/**
* Returns the object stored in the user´s PHP session
* #return Object the stored object
*/
public function restoreFromSession($key) {
$sessionData = $GLOBALS['TSFE']->fe_user->getKey('ses', $this->prefixKey . $key);
return unserialize($sessionData);
}
/**
* Writes an object into the PHP session
* #param $object any serializable object to store into the session
* #return Tx_EXTNAME_Service_SessionHandler this
*/
public function writeToSession($object, $key) {
$sessionData = serialize($object);
$GLOBALS['TSFE']->fe_user->setKey('ses', $this->prefixKey . $key, $sessionData);
$GLOBALS['TSFE']->fe_user->storeSessionData();
return $this;
}
/**
* Cleans up the session: removes the stored object from the PHP session
* #return Tx_EXTNAME_Service_SessionHandler this
*/
public function cleanUpSession($key) {
$GLOBALS['TSFE']->fe_user->setKey('ses', $this->prefixKey . $key, NULL);
$GLOBALS['TSFE']->fe_user->storeSessionData();
return $this;
}
public function setPrefixKey($prefixKey) {
$this->prefixKey = $prefixKey;
}
}
?>
Inject this class into your controller
/**
*
* #var Tx_EXTNAME_Service_SessionHandler
*/
protected $sessionHandler;
/**
*
* #param Tx_EXTNAME_Service_SessionHandler $sessionHandler
*/
public function injectSessionHandler(Tx_EXTNAME_Service_SessionHandler $sessionHandler) {
$this->sessionHandler = $sessionHandler;
}
Now you can use this session handler like this.
// Write your object into session
$this->sessionHandler->writeToSession('KEY_FOR_THIS_PROCESS');
// Get your object from session
$this->sessionHandler->restoreFromSession('KEY_FOR_THIS_PROCESS');
// And after all maybe you will clean the session (delete)
$this->sessionHandler->cleanUpSession('KEY_FOR_THIS_PROCESS');
Rename Tx_EXTNAME and tx_extname with your extension name and pay attention to put the session handler class into the right directory (Classes -> Service -> SessionHandler.php).
You can store any data, not only objects.
HTH
From Typo3 v7 you can also copy the native session handler (\TYPO3\CMS\Form\Utility\SessionUtility) for forms and change it to your needs. The Class makes a different between normal and logged in users and it support multiple session data seperated by the sessionPrefix.
I did the same and generalized the class for a more common purpose. I only removed one method, change the variables name and added the method hasSessionKey(). Here is my complete example:
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
/**
* Class SessionUtility
*
* this is just a adapted version from \TYPO3\CMS\Form\Utility\SessionUtility,
* but more generalized without special behavior for form
*
*
*/
class SessionUtility {
/**
* Session data
*
* #var array
*/
protected $sessionData = array();
/**
* Prefix for the session
*
* #var string
*/
protected $sessionPrefix = '';
/**
* #var TypoScriptFrontendController
*/
protected $frontendController;
/**
* Constructor
*/
public function __construct()
{
$this->frontendController = $GLOBALS['TSFE'];
}
/**
* Init Session
*
* #param string $sessionPrefix
* #return void
*/
public function initSession($sessionPrefix = '')
{
$this->setSessionPrefix($sessionPrefix);
if ($this->frontendController->loginUser) {
$this->sessionData = $this->frontendController->fe_user->getKey('user', $this->sessionPrefix);
} else {
$this->sessionData = $this->frontendController->fe_user->getKey('ses', $this->sessionPrefix);
}
}
/**
* Stores current session
*
* #return void
*/
public function storeSession()
{
if ($this->frontendController->loginUser) {
$this->frontendController->fe_user->setKey('user', $this->sessionPrefix, $this->getSessionData());
} else {
$this->frontendController->fe_user->setKey('ses', $this->sessionPrefix, $this->getSessionData());
}
$this->frontendController->storeSessionData();
}
/**
* Destroy the session data for the form
*
* #return void
*/
public function destroySession()
{
if ($this->frontendController->loginUser) {
$this->frontendController->fe_user->setKey('user', $this->sessionPrefix, null);
} else {
$this->frontendController->fe_user->setKey('ses', $this->sessionPrefix, null);
}
$this->frontendController->storeSessionData();
}
/**
* Set the session Data by $key
*
* #param string $key
* #param string $value
* #return void
*/
public function setSessionData($key, $value)
{
$this->sessionData[$key] = $value;
$this->storeSession();
}
/**
* Retrieve a member of the $sessionData variable
*
* If no $key is passed, returns the entire $sessionData array
*
* #param string $key Parameter to search for
* #param mixed $default Default value to use if key not found
* #return mixed Returns NULL if key does not exist
*/
public function getSessionData($key = null, $default = null)
{
if ($key === null) {
return $this->sessionData;
}
return isset($this->sessionData[$key]) ? $this->sessionData[$key] : $default;
}
/**
* Set the s prefix
*
* #param string $sessionPrefix
*
*/
public function setSessionPrefix($sessionPrefix)
{
$this->sessionPrefix = $sessionPrefix;
}
/**
* #param string $key
*
* #return bool
*/
public function hasSessionKey($key) {
return isset($this->sessionData[$key]);
}
}
Don't forget to call the initSession first, every time you want use any method of this class