Couldn't extend session timeout in ZF2 - php

I'm saving my session data on my database(mongodb), the customer asked that he want the system to be idle for 2 hours(he has videos on the site which may take 2 hours to finish, so he asked to set session timeout value as 2 hour). I did it as Zend Framework suggested. see my config.php below
return array(
'env2_session' => array(
'config' => array(
'class' => 'Zend\Session\Config\SessionConfig',
'options' => array(
'name' => 'test',
'remember_me_seconds' => 7200,
'gc_maxlifetime' => 7200,
),
),
'mongo_handler' => array(
'options' => array(
'class' => 'Zend\Session\SaveHandler\MongoDBOptions',
'collection' => 'sessions',
),
),
'save_handler' => 'Env2Session/Mongo/Handler',
'validators' => array(
array(
'Zend\Session\Validator\RemoteAddr',
'Zend\Session\Validator\HttpUserAgent',
),
),
),
);
But this is not the correct code as I couldn't see the session extended. it still get timed out after 24 minutes.
It will work if I add 'cookie_lifetime' => 7200 after 'gc_maxlifetime' => 7200 But this get timedout even if I'm using the site.
I want the timeout only when the system is idle. Please get me some thing on this.
Here is the save handler code which I written in Module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Env2Session/Mongo/Handler' => function ($sm) {
$config = $sm->get('config');
$session = $config['env2_session'];
$mongo = $sm->get('Env2\Mongo');
$class = isset($session['mongo_handler']['options']['class']) ? $session['mongo_handler']['options']['class'] : 'Zend\Session\SaveHandler\MongoDBOptions';
$options = array();
$options['collection'] = $session['mongo_handler']['options']['collection'];
$options['database'] = $config['db']['mongo']['db_name'];
$mongoOption = new $class($options);
$sessionSaveHandler = new MongoDB($mongo, $mongoOption);
return $sessionSaveHandler;
},
'Env2Session' => function ($sm) {
$config = $sm->get('config');
if (isset($config['env2_session'])) {
$session = $config['env2_session'];
$sessionConfig = null;
if (isset($session['config'])) {
$class = isset($session['config']['class']) ? $session['config']['class'] : 'Zend\Session\Config\SessionConfig';
$options = isset($session['config']['options']) ? $session['config']['options'] : array();
$sessionConfig = new $class();
$sessionConfig->setOptions($options);
}
$sessionStorage = null;
if (isset($session['storage'])) {
$class = $session['storage'];
$sessionStorage = new $class();
}
$sessionSaveHandler = null;
if (isset($session['save_handler'])) {
$sessionSaveHandler = $sm->get($session['save_handler']);
}
$sessionManager = new SessionManager($sessionConfig, $sessionStorage, $sessionSaveHandler);
if (isset($session['validator'])) {
$chain = $sessionManager->getValidatorChain();
foreach ($session['validator'] as $validator) {
$validator = new $validator();
$chain->attach('session.validate', array($validator, 'isValid'));
}
}
} else {
$sessionManager = new SessionManager();
}
Container::setDefaultManager($sessionManager);
return $sessionManager;
}
),
);
}

I was struggling with the same issue for zend session timeouts. Finally I implemented own solution for this case. I set up the expiration time which is refreshed during each request. But if user is not active, the time will expire and session will be destroyed.
I put all tutorial how to do it here: http://blog.tulikowski.com/zend-framework-2-implementation-of-session-authentication-timeouts/

Go to your autoload/global.php and either create or edit this key:
'session_config' => array
(
'cache_expire' => 60*60*2,
'name' => 'sessionName',
'cookie_lifetime' => 60*60*2,
'gc_maxlifetime' => 60*60*2,
'cookie_path' => '/',
'cookie_secure' => FALSE,
'remember_me_seconds' => 60*60*2,
'use_cookies' => true,
),

Related

How to send HTTP Cookies to another ZF2 Controller?

I have two controllers. One of them is called OAMLController and the other is called LoginController. I would like to set HTTP Cookies in OAMLController and then make a call to LoginController and read it in this controller.
I know how to do this in PHP, but I don't know how to do this in Zend Framework 2.
PHP (OAML.php):
setcookie("_ga", "GA1.2.1622977711.1433494392", 0, "/", "http://gnsys.local");
setcookie("_gat", "1", 0, "/", "http://gnsys.local");
header("Location: http://gnsys.local/publico/login.php");
PHP (login.php):
$cookie = "";
foreach (getallheaders() as $name => $value) {
echo "$name: $value</br>";
if ($name == "Cookie")
$cookie = $value;
}
I have tried to follow the ZF2 tutorial but is so confusing.
More questions:
I have redirect to the other controller using $this->redirect()->toUrl($url).
$cookie = new \Zend\Http\Header\SetCookie("param1", "Hola", null, null, "http://gnsys.local", null, null, null, null);
$this->getResponse()->getHeaders()->addHeader($cookie);
return $this->redirect()->toUrl("http://gnsys.local/publico/login");
Because if I redirect with:
$controllerName = "LoginController";
$actionName = "index";
return $this->redirect()->toRoute(
"publico",
array(
"controller" => $controllerName,
"action" => $actionName
));
I always access to http://gnsys.local/publico and not to where I want http://gnsys.local/publico/login.
Another question, in LoginController I can't read the cookie. If I check the cookies via Firebug I can see that I have created the cookie in ".gnsys.local" domain and not in "gnsys.local" domain.
Why has that happened? If I make the redirect using toRoute or toUrl I create the cookie on the same domain ".gnsys.local" and not in "gnsys.local".
module.config:
'router' => array(
'routes' => array(
// The following is a route to simplify getting started creating
// new controllers and actions without needing to create a new
// module. Simply drop new controllers in, and you can access them
// using the path /application/:controller/:action
'publico' => array(
'type' => 'Literal',
'options' => array(
'route' => '/publico',
'defaults' => array(
'__NAMESPACE__' => 'Publico\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
Updated 2:
Finally, the redirection works fine with the solution from Jangya Satapathy. But I have a new problem and this is that I can't read the cookie because the domain is not correct. With these code I create a cookie with domain ".gnsys.local" and not with the domain "gnsys.local"
$cookie = new \Zend\Http\Header\SetCookie("param1", "Hola", null, null, "http://gnsys.local", null, null, null, null);
$this->getResponse()->getHeaders()->addHeader($cookie);
$controllerName = "login";
$actionName = "index";
return $this->redirect()->toRoute(
"publico/default",
array(
"controller" => $controllerName,
"action" => $actionName
));
So, when I try to write the value of cookie "param1", I've got the next error:
Notice: Undefined index: param1 in /var/www/html/gnsys/module/Publico/src/Publico/Controller/LoginController.php
If we check the value of the cookies with firebug, we've got the next screen capture:
What am I doing wrong?
Updated 3:
I don't understand what happened but getCookie is null.
getcookie IS NULL
And print_r($this->getRequest()->getCookie()); doesn't write anything.
$getcookie = $this->getRequest()->getCookie(); // returns object of Zend\Http\Header\Cookie
if ($getcookie != null)
echo "getcookie is NOT NULL";
else
echo "getcookie IS NULL";
print_r($this->getRequest()->getCookie());
return new ViewModel();
Updated 4:
I have found the cookie, but I cannot retrieve its value. To find the cookie, I have to indicate the path where I'm going to read it then.
$cookie = new \Zend\Http\Header\SetCookie("param1", "Hola", 0, "/publico/login/index", "gnsys.local");
$this->getResponse()->getHeaders()->addHeader($cookie);
$controllerName = "login";
$actionName = "index";
return $this->redirect()->toRoute(
"publico/default",
array(
"controller" => $controllerName,
"action" => $actionName
));
And, now I have this exit ...
getcookie is NOT NULL
Zend\Http\Header\Cookie Object ( [encodeValue:protected] => 1 [storage:ArrayObject:private] => Array ( [zdt-hidden] => 0 ) )
If I try to retrieve the value of the cookie through
$cookie = $getcookie->param1;
I've got the next error ...
Notice: Undefined index: param1 in /var/www/html/gnsys/module/Publico/src/Publico/Controller/LoginController.php on line 84
If I try to get all the values from $getcookie
foreach ($getcookie as $key => $value){
echo "Key: " . $key . " Value: " . $value . "<br />";
}
And I've got ...
Key: zdt-hidden Value: 0
Update 5:
I don't understand anything here. I'm not creating the cookie with these code!
$cookie = new \Zend\Http\Header\SetCookie("param1", "Hola", 0, "/", "http://gnsys.local");
$this->getResponse()->getHeaders()->addHeader($cookie);
$controllerName = "login";
$actionName = "index";
return $this->redirect()->toRoute(
"publico/default",
array(
"controller" => $controllerName,
"action" => $actionName
));
Checking the cookies using firebug we can't see the cookie.
In your cookie set action:
Public function cookiesetAction(){
$cookie = new \Zend\Http\Header\SetCookie($name, $value, $expires, $path, $domain, $secure, $httponly, $maxAge, $version);
$this->getResponse()->getHeaders()->addHeader($cookie);
return $this->redirect()->toRoute('cookieget'); //to your login controller
}
In your cookie get action:
public function cookiegetAction(){
$getcookie = $this->getRequest()->getCookie(); // returns object of Zend\Http\Header\Cookie
$getcookie->name1; // value1
$getcookie->name2; // value2
return new ViewModel();
}
Question about cookies in ZF2.
Answer Update
Add child route followed by the main route.
return $this->redirect()->toRoute('publicio/default',array(
'controller'=>$controllername,
'action'=>$actioname
));

Curl Exception 7 PHP and Guzzle with Elasticsearch

I am trying to index documents using the php client for elastic search which uses Guzzle. After compiling my php script I am getting an error that says Internal Server Error, code 500. After doing some research this seems to be an issue with connecting to a server but the strange part is that everything I'm trying to do is set up on the same machine. My instance of Elasticsearch, my documents I'm trying to index, and my php scripts are all saved and running on the same machine. This is my PHP Script:
<?php
require '/home/aharmon/vendor/autoload.php';
$client = new Elasticsearch\Client();
$root = realpath('/home/aharmon/elkdata/for_elk_test_2014_11_24/Agencies');
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD);
$paths = array($root);
foreach ($iter as $path => $dir) {
if ($dir -> isDir()) {
$paths[] = $path;
}
}
//Create the index and mappings
$mapping['index'] = 'rvuehistoricaldocuments2009-2013'; //mapping code
$mapping['body'] = array (
'mappings' => array (
'documents' => array (
'_source' => array (
'enabled' => true
),
'properties' => array(
'doc_name' => array(
'type' => 'string',
'analyzer' => 'standard'
),
'description' => array(
'type' => 'string'
)
)
)
)
);
//Now index the documents
for ($i = 0; $i <= 10000; $i++) {
$params ['body'] [] = array(
'index' => array(
'_id' => $i
)
);
$params ['body'] [] = array(
'type' => 'documents',
'body' => array(
'foo' => 'bar'//Document body goes here
)
);
//Every 1000 documents stop and send the bulk request.
if($i % 1000) {
$responses = $client->bulk($params);
// erase the old bulk request
$params = array();
// unset the bulk response when you are done to save memory
unset($responses);
}
}
$client ->indices()->create($mapping)
?>
If anyone has seen this before or has an inclination as to what the issue the help would be greatly appreciated. I had a similar issue before when I tried to set up SSH but I got the firewall all configured and got SSH working so I'm not sure why this is happening.
check this link it is ok for me :
http://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_index_operations.html#_put_mappings_api
<?php
// Set the index and type
$params['index'] = 'my_index';
$params['type'] = 'my_type2';
// Adding a new type to an existing index
$myTypeMapping2 = array(
'_source' => array(
'enabled' => true
),
'properties' => array(
'first_name' => array(
'type' => 'string',
'analyzer' => 'standard'
),
'age' => array(
'type' => 'integer'
)
)
);
$params['body']['my_type2'] = $myTypeMapping2;
// Update the index mapping
$client->indices()->putMapping($params);

Prestashop error "invalid security token"

im creating a new module for prestashop 1.5.6 and im having some problems with it.
The module has to send sms to the costumers and it has to be an option of the back-Office menu.
I have created the module with the install and uninstall functions and added the tabs to the back-office menu, but im a newbie in prestashop so i don´t know how to make the AdminMyModuleController.php and when i try to click the tab of the module it says "INVALID SECURITY TOKEN", i don´t know how resolve this issue because i don´t know much of security.
If someone can add me on facebook or whatever to help me would be amazing.
Here is the code of the mymodule.php:
private function _createTab()
{
// Tab Raiz
$data = array(
'id_tab' => '',
'id_parent' => 0,
'class_name' => 'Empty',
'module' => 'mymodule',
'position' => 14, 'active' => 1
);
/* Insert the data to the tab table*/
$res = Db::getInstance()->insert('tab', $data);
//Get last insert id from db which will be the new tab id
$id_tabP = Db::getInstance()->Insert_ID();
//Define tab multi language data
$data_lang = array(
'id_tab' => $id_tabP,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'SMS a clientes'
);
// Now insert the tab lang data
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Configuracion
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminMymodule',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Configuracion'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Enviar Sms
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminEnviar',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Enviar SMS'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
return true;
}
Thanks
As Lliw said, you must use InstallModuleTab function.
private function installModuleTab($tabClass, $tabName, $idTabParent)
{
$pass = true;
$tab = new Tab();
$tab->name = $tabName;
$tab->class_name = $tabClass;
$tab->module = $this->name; // defined in __construct() function
$tab->id_parent = $idTabParent;
$pass = $tab->save();
return($pass);
}
You can put all in your Install function. For example for your first tab:
public function install()
{
if(!parent::install()
|| !$this->installModuleTab('Empty', array(1 => 'SMS a clientes'), $idTabParent = 0))
return false;
return true;
}
You can set languages with the following array:
array(1 => 'SMS a clientes', 2 => 'Language 2', 3 => 'Language 3')
Then you must create the AdminMyModuleController.php file
It's the wrong way to create a module tab. You should use this function in your install() :
$this->installModuleTab('AdminMyModule', array(1 => 'Attribute description'), $idTabParent = 9);
Then create an AdminMyModuleController.php in your module folder/controllers/admin/AdminMyModuleController.php
But you will need to set some function to see something displayed, i'll make a tutorial for that but until i do it, you can look in another admincontroller from the prestashop core and do the same.

Yii Session not getting over

I am trying to change the default session time out value. In my controller i have done this:
public function beforeAction($action) {
$session = new CHttpSession;
$timeout = $session->getTimeout();
if ($timeout != 10) {
$session->setTimeout(10);
}
return true;
}
But my session never gets timed out an i can access the page even after being inactive for 10 sec.
I also tried to do it through config by session component like this:
'session' => array(
'sessionName' => SITE_SESSION_COOKIE_NAME,
'class' => 'CHttpSession',
'timeout' => 10
),
but same result. Session dosent time out! Am I missing out on something?
Try to turn off autostart session in configs:
'session' => array(
'sessionName' => SITE_SESSION_COOKIE_NAME,
'class' => 'CHttpSession',
'autoStart' => false
),
In this case you need manually starting session: Yii::app()->session->open(), but BEFORE IT for changing life time try do:
Yii::app()->session->open($session_lifetime);
$cook_p = Yii::app()->session->getCookieParams();
$cook_p['lifetime'] = $session_lifetime;
Yii::app()->session->setCookieParams($cook_p);
OR you may inherit CHttpSession with new parameter lifetime and do it in method init():
class MyHttpSession extends CHttpSession{
public $lifetime = false;
public function init()
{
if($this->lifetime !== false){
$cook_p = $this->getCookieParams();
$cook_p['lifetime'] = $this->lifetime;
$this->setCookieParams($cook_p);
$this->setTimeout($this->lifetime);
}
parent::init();
}
}
and in configs:
'session' => array(
'sessionName' => SITE_SESSION_COOKIE_NAME,
'class' => 'MyHttpSession',
'lifetime' => 60 // 1 minute
),
The class in the session array should apparently be CDbHttpSession for this to work.
See here for a similar issue..
for session timeout based on user being in-active for 30 minutes, in configs:
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=> true,
'autoRenewCookie'=> true,
'authTimeout' => 1800
),
'session' => array(
'class' => 'FrontCHttpSession',
'savePath' => dirname(__FILE__),
'cookieMode' => 'allow',
'cookieParams' => array(
'path' => '/',
'domain' => 'mydomain.com',
'httpOnly' => true,
'lifetime' => 1800
),
'timeout' => 1800
),
Extended session class, similar idea can be used for CDbHttpSession
<?php
class FrontCHttpSession extends CHttpSession
{
/*default is 0 which means the cookie lifetime will last as long as the browser is open*/
private $_clientLifetime;
/*time in seconds how long the session should remain open after user in-activity*/
private $_sessionTimeout;
/*cookie params defined in config*/
private $_cookieParams;
/**
* Starts the session if it has not started yet.
*/
public function open()
{
$this->_cookieParams = $this->getCookieParams();
$this->_clientLifetime = $this->_cookieParams['lifetime'];
$this->_sessionTimeout = $this->timeout;
if($this->getUseCustomStorage())
#session_set_save_handler(array($this,'openSession'),
array($this,'closeSession'),
array($this,'readSession'),
array($this,'writeSession'),
array($this,'destroySession'),
array($this,'gcSession'));
//session is already started, check if session has been not been active longer than timeout
if (session_id() != '')
{
if ($this->get('last_active') < time() - $this->_sessionTimeout)
{
$this->destroy();
}
else if ($this->_clientLifetime > 0)
{
$this->updateSessionCookieExpire();
}
}
#session_set_cookie_params($this->_clientLifetime, array($this->_cookieParams['path'],
$this->_cookieParams['domain'], $this->_cookieParams['secure'], $this->_cookieParams['httpOnly']));
#session_start();
$this->add('last_active', time());
if(YII_DEBUG && session_id()=='')
{
$message=Yii::t('yii','Failed to start session.');
if(function_exists('error_get_last'))
{
$error=error_get_last();
if(isset($error['message']))
$message=$error['message'];
}
Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
}
}
public function updateSessionCookieExpire()
{
if (isset(Yii::app()->request->cookies[$this->getSessionName()]))
{
$c = Yii::app()->request->cookies[$this->getSessionName()];
$c->expire = time() + $this->_clientLifetime;
$c->path = $this->_cookieParams['path'];
$c->domain = $this->_cookieParams['domain'];
$c->httpOnly = $this->_cookieParams['httponly'];
$c->secure = $this->_cookieParams['secure'];
Yii::app()->request->cookies[$this->getSessionName()] = $c;
}
}
}

PHP, MYSQL Web Service with nusoap

I'm starting to learn about web services and I'm doing some tests.
I'm trying to write a service to pass all the data of a table into my client but i can't make it work.
The first one 'servei' works, but the second doesn't.
Any suggestions will be appreciated. Thanks
service.php
require 'lib/nusoap.php';
$server = new nusoap_server();
$server->configureWSDL("test" . "urn:test");
include 'functions.php';
$server->wsdl->addComplexType('servei', 'complexType', 'struct', 'all', '', array(
'preu_antic' => array('name' => 'preu_antic', 'type' => 'xsd:float'),
'preu_actual' => array('name' => 'preu_actual', 'type' => 'xsd:float'),
'descompte_servei' => array('name' => 'descompte_servei', 'type' => 'xsd:float'),
));
$server->wsdl->addComplexType('ServiceTypes', 'complexType', 'struct', 'all', '', array(
'id_tipus_servei' => array('name' => 'id_tipus_servei', 'type' => 'xsd:inter'),
'nom_tipus_servei' => array('name' => 'nom_tipus_servei', 'type' => 'xsd:string'),
'descripcio_tipus_servei' => array('name' => 'descripcio_tipus_servei', 'type' => 'xsd:string'),
));
$server->wsdl->addComplexType('ArrayOfServiceTypes', 'complexType', 'array', '', 'SOAP-ENC:Array', array(), array(
array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:ServiceTypes[]')), 'tns:ServiceTypes');
$server->register('servei', array("id_servei" => 'xsd:inter'), array("return" => 'tns:servei'));
$server->register('getServiceTypes', array("idioma" => 'xsd:string'), array("return" => 'tns:ArrayOfServiceTypes'));
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
functions.php
function servei($id){
conexio();
$query_servei = mysql_query("SELECT * FROM servei WHERE id_servei = '$id'")or die(mysql_error());
$row = mysql_fetch_array($query_servei);
$preu_antic = $row['preu_antic'];
$preu_actual = $row['preu_actual'];
$descompte_servei = $row['descompte_servei'];
$servei = array('preu_antic'=>$preu_antic,'preu_actual'=>$preu_actual,'descompte_servei'=>$descompte_servei);
return $servei;
}
function getServiceTypes($idioma){
conexio();
$query = mysql_query("SELECT id_tipus_servei, nom_tipus_servei, descripcio_tipus_servei FROM idioma_tipus_servei WHERE id_idioma = '$idioma'") or die(mysql_error());
$n = 0;
while ($row = mysql_fetch_array($query)) {
$result[$n]['id_tipus_servei'] = $row['id_tipus_servei'];
$result[$n]['nom_tipus_servei'] = $row['nom_tipus_servei'];
$result[$n]['descripcio_tipus_servei'] = $row['descripcio_tipus_servei'];
$n++;
}
return $result;
}
?>
client.php
<?php
require 'lib/nusoap.php';
include 'functions.php';
$client = new nusoap_client("http://192.168.8.155:8090/webservice/service.php?wsdl");
//$id=1;
// $servei = $client -> call('servei',array("id_servei"=>"$id"));
// print_r($servei);
$idioma ='ca';
$servicetypes = $client -> call('getServiceTypes',array("idioma"=>"$idioma"));
print_r($servicetypes);
?>
OK, I handled it.
If you are using PHP 5.4 you have to comment line 6132 in nusoap.php.
Couldn't this be fixed if we were to change it from:
$this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]");
To:
$this->debug("serializing array element: $k, $v of type: " . $typeDef['arrayType'] );

Categories