Zend Framework 1 - Zend Caching - php

I am working on optimizing Zend Framework Application with Doctrine ORM. I can't figure it out what particular code would I use in my controller to get this caching. Whenever I pass again the same url it should use the cache code instead of processing that logic again.
My Bootstrap file for cache looks like this:-
protected function _initCache() {
$frontendOptions = array(
'lifetime' => 7200, 'content_type_memorization' => true,
'default_options' => array(
'cache' => true,
'cache_with_get_variables' => true,
'cache_with_post_variables' => true,
'cache_with_session_variables' => true,
'cache_with_cookie_variables' => true, ),
'regexps' => array(
// cache the whole IndexController
'^/.*' => array('cache' => true),
'^/index/' => array('cache' => true),
// place more controller links here to cache them
)
);
$backendOptions = array(
'cache_dir' => APPLICATION_PATH ."/../cache" // Directory where to put the cache files
);
$cache = Zend_Cache::factory('Page', 'File', $frontendOptions, $backendOptions);
$cache->start();
Zend_Registry::set("cache", $cache);
}
Any help would be appreciated.

Check this below code to set cache if not exist or get cache if exists.
$result =””;
$cache = Zend_Registry::get('cache');
if(!$result = $cache->load('mydata')) {
echo 'caching the data…..';
$data=array(1,2,3); // demo data which you want to store in cache
$cache->save($data, 'mydata');
} else {
echo 'retrieving cache data…….';
Zend_Debug::dump($result);
}

Related

PHP script to clear cache in Joomla 3.x

I created the following script and put it to cron job on server. Unfortunately it does not work.
include 'includes/defines.php';
include 'includes/framework.php';
$conf = JFactory::getConfig();
$options = array(
'defaultgroup' => '',
'storage' => $conf->get('cache_handler', ''),
'caching' => true,
'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
);
$cache = JCache::getInstance('', $options);
$cache->clean('cachegroup');
Do you have an idea what is wrong?

ZF2 RememberMe expires after closing Browser

I want a "remember-me" cookie for my login form and get it work until I reopen the browser. I am using the Zend Framework 2 to get it done.
I set up a form with a checkbox and have this in my controller after validating the form:
$userSession = new Container("test");
$sessionManager = $userSession->getManager();
$sessionManager->rememberMe(1209600);
$sessionManager->start();
In the module.config.php I have the following settings for the session:
'session' => array(
'name' => 'Test_SESSION',
'save_path' => realpath('C:\xampp\htdocs\Workspace\test\data\session'),
'remember_me_seconds' => 1209600,
'cookie_lifetime' => 1209600,
'use_cookies' => true,
'cookie_httponly' => true,
),
And finally in module.php:
$session = new SessionConfig();
$session->setOptions($this->serviceLocator->get("config")["session"]);
I searched through the web for any advises and tried something, but at least when I close the browser the cookie is deleted. Firefox settings of deleting cookies were checked also, so they won't be automatically deleted. Does any one has a successful solution or hint?
Edit: When I take the code of newtake and add $sessionManager->rememberMe(); to it, the session is still alive after closing browser, but I can't login anymore even the login process is successfully done. Anyone heard from this curiosity?
Need setup SessionConfig to SessionManager. It is my config
'service_manager' => array(
'factories' => array(
'Zend\Session\SessionManager' => function ($sm) {
$sessionConfig = new \Zend\Session\Config\SessionConfig();
$sessionConfig->setOptions([
'use_cookies' => true,
'gc_maxlifetime' => 1728000,
'cookie_lifetime' => 1728000,
'name' => 'COOKIE_NAME',
]);
$sessionManager = new \Zend\Session\SessionManager($sessionConfig);
$sessionManager->start();
return $sessionManager;
}
)
)

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
));

Yii session storage, lifetime and cookies

Working with the Yii framework in the config-file session storaged is handled as follows:
'session' => array(
//'sessionName' => 'SomeSession',
'class' => 'CDbHttpSession',
'connectionID' => 'SomeConnection',
'autoCreateSessionTable' => false,
'sessionTableName' => 'SomeTable',
'autoStart' => 'false',
'cookieMode' => 'only',
'useTransparentSessionID' => false,
'timeout' => CSESSIONTIMEOUT,
'cookieParams' => array(
'path' => '/',
'domain' => '.somedomain.extension',
'expire' => time()+5256000,
'lifetime' => time()+5256000,
//'httpOnly' => true,
),
),
So as you see sessions are stored in a table in a database with a given lifetime. But if I check the stored sessions in the database they are not stored with the given lifetime they are stored with a lifetime of a year.
The only thing I can find in our application that has a lifetime of a year are the cookies. For example like this:
setcookie("cookie_name", $someValue, time()+31536000, "/", "somedomain");
What is confusing for me are the cookies in our application. Could it be possible that this overrides the Yii session storage config?
UPDATE
I also came across this line of code
$_SESSION['POLL_'.$idPoll.'somekey'] = strtotime("now");
And that line of code inserted a session record in the database. But that record also has an lifetime of a year. How is this possible?
You need to add timeout param to config like this:
'session' => array(
'class' => 'CDbHttpSession',
'timeout' => 5256000,
// ...
Try Cookies Like this : -
if (isset($_POST['remember'])) {
$cookieUsername = new CHttpCookie('phoenix_admin_username', $_POST['LoginForm']['username']);
$cookiePassword = new CHttpCookie('phoenix_admin_password', base64_encode($_POST['LoginForm']['password']));
$cookieUsername->expire = time() + 604800;
$cookiePassword->expire = time() + 604800;
Yii::app()->request->cookies['phoenix_admin_username'] = $cookieUsername;
Yii::app()->request->cookies['phoenix_admin_password'] = $cookiePassword;
}
////////////Check like this//////////////
if(isset(Yii::app()->request->cookies['phoenix_admin_username'])){
$model->username = Yii::app()->request->cookies['phoenix_admin_username']->value;
$model->password = base64_decode(Yii::app()->request->cookies['phoenix_admin_password']->value);
}else{
$model->username = "";
$model->password = "";
}

Zend Framework 2 session life time

I am trying to set the max life time of a session with the \Zend\Session\Container. To test it I put it to 1 sec.
Now I looked at the docs
So i did
$config = new StandardConfig();
$config->setOptions(array(
'remember_me_seconds' => 1,
));
$manager = new SessionManager($config);
$session = new Container('user', $manager);
But no success. Then I started googling and found this answer
So I made the config to
return array(
'session' => array(
'remember_me_seconds' => 2419200,
'use_cookies' => true,
'cookie_httponly' => true,
),
);
(the config worked and was loaded into the manager) but again no success
So I continued searching and found this answer
But again no success.
So after all the searching I couldn't get it working, so now I hope some one else got it working and can help me.
Well I finaly found out what the issue was.
The problem was that I used
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(array(
'use_cookies' => true,
'cookie_httponly' => true,
'gc_maxlifetime' => $config['authTimeout'],
));
$manager = new SessionManager($sessionConfig);
This "worked" the only issue was that there was set a cookie with the lifetime session. This ment different things in browsers. Ie in chrome it is destroyed if you close the tab, so no matter how high the gc_maxlifetime it would not work.
So an easy fix would be the following
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(array(
'use_cookies' => true,
'cookie_httponly' => true,
'gc_maxlifetime' => $config['authTimeout'],
'cookie_lifetime' => $config['authTimeout'],
));
$manager = new SessionManager($sessionConfig);
Hope it would help some one in the futue
$config['authTimeout'] is a positive integer value
$config = new StandardConfig();
$config->setOptions(array(
'cookie_lifetime' => '2419200',
'gc_maxlifetime' => '2419200'
));
Change the value of 2419200 to how many seconds you actually want.
In application global.php or you can do it in module config:
'session_config' => array(
'name' => 'your session name',
'remember_me_seconds' => 60 * 60 * 24 * 30*3,
'use_cookies' => true,
'cookie_httponly' => true,
),
check Zend\Session\Service\SessionConfig.

Categories