I found this topic Zend Framework 2 - Cookie Concept while I was searching for info about setting cookie in ZF2, but seems like information included in that topic are out of date.
I have tried following code:
public function indexAction()
{
$request = $this->getRequest()->getHeaders()->get('Set-Cookie')->foo = 'bar;
$response = $this->getResponse()->getCookie()->baz = 'test';
var_dump($_COOKIE);
...
return new ViewModel();
}
Both lines output warning:
Warning: Creating default object from empty value
I tried also:
public function indexAction()
{
$cookie = new SetCookie('test', 'value', 60*60*24); // Zend\Http\Header\SetCookie instance
$header = new Cookie(); // Zend\Http\Cookies instance
$header->addCookie($cookie);
...
return new ViewModel();
}
It doesn't return any error or warning, everything seems to be ok, but when I try var_dump($_COOKIE) it still shows null.
Yes, my browser has enable cookie.
Here is my solution which I'm currently using.
$cookie = new SetCookie('key', 'value', time() + 365 * 60 * 60 * 24); // now + 1 year
$headers = $this->getResponse()->getHeaders();
$headers->addHeader($cookie);
Related
I want to set cookie value in one function and their value use everywhere in cakephp 4 version.
Currently , i can use cookie value inside the only one function which i have set their value.
I can get cookie value in index() function but i can't get cookie value in viewusers() function.
Code is here :
use App\Controller\AppController;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieCollection
use DateTime;
class AdminController extends AppController {
function index(){
$cookie = array();
$cookie['admin_username'] = $requestData['username'];
$cookie['admin_password'] = $requestData['password'];
$cookies = new Cookie('AuthAdmin',$cookie, new DateTime('+1 weeks'));
$response = $this->response->withCookie($cookie);
return $this->redirect('admin/viewusers');
}
function viewusers() {
$cookies = new CookieCollection();
$data = $cookies->get('AuthAdmin');
print_r($data);
// cookie value not found in $data variable.
$response = $this->response->getCookie('Auth.Admin');
print_r($response);
// cookie value not found in $response variable.
}
}
I can get cookie value in index() function but i can't get cookie value in viewusers() function.
Try this:
function index(){
$cookie = array();
$cookie['admin_username'] = $requestData['username'];
$cookie['admin_password'] = $requestData['password'];
$cookies = new Cookie('AuthAdmin',$cookie, new DateTime('+1 weeks'));
return $this
// redirect returns a response object, so you can chain the cookie call onto that
->redirect('admin/viewusers')
// Note that this uses $cookies, not $cookie
->withCookie($cookies);
}
But again, I cannot stress strongly enough that sending a cookie with the user's username and password in it is a very bad thing from a security perspective.
I am trying to write my user ID to cookie. I can catch it from dataLayer variable from server when user is login in but user can be already logged in next session. So I tried to create custom JavaScript code that suppose to check if variable is not undefined and write a cookie and if the cookie exist then returns cookie value.
function() {
if ({{UID dataLayer}}) {
var d = new Date();
d.setTime(d.getTime() + 1000 * 60 * 60 * 24 * 365 * 2);
var expiresdate = 'Expires=' + d.toGMTString();
document.cookie = 'UIDcookie=' + {{UID dataLayer}} + '; ' + expiresdate + '; Path=/';
return {{UID dataLayer}};
} else if ({{UID Cookie}}) {
return {{UID Cookie}};
}
return;
}
But it works only when I'm in tagmanager debug mode, when it's off nothing suppose to happen. So my question is what am I doing wrong?
It's probably a question of timing. Try to fire the tag to the page load, in this way the function in JS variable should be able to read the cookie.
I'm testing my Rest APIs.
I want to pass a parameter to my request.
This is in my controller, I have:
public function index(Request $request)
{
$abuse = Abuse::where('bombId', $request->input('bombId'))->get();
}
Thing is with PhpUnit, I can never simulate the bombId parameter...
Here is my code:
$data['bombId'] = 25; // I also tried $bombId = 25;
$this->get('api/v1/abuse', $data])
->seeJson(['total' => 11]);
$this->assertResponseStatus(200);
EDIT:
When I use:
$this->call('GET','api/v1/abuse', $credentials);
Param is passed, but I can't use anymore SeeJson method :(
Any Idea?
I found my answer with Jeffrey Way:
$response = $this->call('GET', 'api/v1/abuse', $credentials);
$data = $this->parseJson($response);
$this->assertIsJson($data);
$this->assertEquals(11, $data->total);
I'm stuck on a common problem but I don't really know how to get out.
The browsers don't keep the auth session.
Here is my setup.
"application.ini"
resources.session.save_path = ROOT_DIR "/public/session"
resources.session.gc_maxlifetime = 864000
resources.session.remember_me_seconds = 864000
".htaccess"
php_value session.gc_maxlifetime 864000
php_value session.save_path /Users/user/mydomain.com/public/session/
"bootstrap.php" (_initSessionNamespaces it's the first method I call)
protected function _initSessionNamespaces()
{
$this->bootstrap('session');
Zend_Session::start();
}
"SigninController.php"
// set adapter
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('user')
->setIdentityColumn('email')
->setCredentialColumn('password')
->setCredentialTreatment($salt)
->setIdentity($values['email'])
->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
$user = $authAdapter->getResultRowObject();
$auth->getStorage()->write($user);
// init session cookie
$session_auth = new Zend_Session_Namespace('identity');
$session_auth->setExpirationSeconds(864000);
return true;
}
the session file that has been created in the directory is this:
language|a:1:{s:6:"locale";s:2:"en";}identity|a:2:{s:14:"filterDistance";i:5;s:5:"email";s:15:"test#test.com";}Zend_Auth|a:1:{s:7:"storage";O:8:"stdClass":20:{s:2:"id";s:20:"8c3b329b0f3d71f4566c";s:12:"date_created";s:19:"2012-12-19 20:30:29";s:12:"date_updated";s:19:"2013-01-12 00:02:19";s:14:"date_lastlogin";s:19:"2013-01-16 15:30:01";s:7:"site_id";s:4:"this";s:14:"site_lastlogin";s:4:"this";s:6:"active";s:1:"1";s:4:"role";s:5:"admin";s:8:"username";s:5:"test";s:8:"password";s:40:"63fb7f1941083ca0284481d8ad557e2b0c5bf5f4";s:4:"salt";s:40:"70be1adbff1c0bd6f82sc1fcaf6d2fef3c869b6c";s:10:"first_name";s:5:"pippo";s:9:"last_name";s:0:"";s:5:"email";s:15:"test#test.com";}}__ZF|a:1:{s:9:"Zend_Auth";a:1:{s:3:"ENT";i:865358347332;}}
And usually in a Controller I call the user info in this way
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->info = $auth->getIdentity();
}
When I restart the browser it create a new empty session file like this:
language|a:1:{s:6:"locale";s:2:"it";}
I'm stuck here for 2 days... what can I do??
I solved it adding this in application.ini
resources.session.cookie_lifetime = 864000
I think this could help someone :)
I have a client input form that has the following two reg expressions that works when creating a client but not when updating a client. The update form is a class that extends the crate form.
// Create text input for mobile
$mobile = new Zend_Form_Element_Text ('mobile');
$mobile->setLabel ('Mobile Number:')
->setDescription('Enter mobile in the format 353XXYYYYYYY')
->setOptions(array('size'=>'14'))
->setRequired(false)
->addValidator('Regex',false,array(
'pattern'=>'/^\d{12}$/',
'messages'=>array(
Zend_Validate_Regex::INVALID => '\'%value%\' Invalid mobile number it does not match the required format 353XXYYYYYYY',
Zend_Validate_Regex::NOT_MATCH =>'\'%value%\'does not match the required format 353XXXXXXXX')
)
)
->addFilter('HtmlEntities')
->addFilter('StringTrim');
// Create text input for landline
$landline = new Zend_Form_Element_Text ('landLine');
$landline->setLabel ('Phone Number:')
->setDescription('Enter phone number in the format +353(0) X YYY YYYZ')
->setOptions(array('size'=>'20'))
->setRequired(false)
->addValidator('StringLength', false, array('min' => 8))
->addValidator('Regex', false, array(
'pattern' => '/^\+353\(0\)\s\d\s\d{3}\s\d{3,4}$/',
'messages' => array(
Zend_Validate_Regex::INVALID =>
'\'%value%\' In valid Phone number does not match required number format +353(0) X YYY YYYZ',
Zend_Validate_Regex::NOT_MATCH =>
'\'%value%\' does not match required number format of +353(0) X YYY YYYZ'
)
))
->addFilter('HtmlEntities')
->addFilter('StringTrim');
When I enter an invalid mobile or land line number when creating a client the reg expression works and prevents the record from being saved.
However when I enter an invalid mobile or land line number when updating a client the reg expression fails and an 404 error occurs.
I think that the issue may be related to the get section of my update action within my controller as shown below but I can't figure out what is causing this as the route I have configured in my ini file retrieves the record as required.
public function updateAction(){
// generate input form
$form = new PetManager_Form_UpdateClient;
$this->view->form=$form;
/* if the requrest was made via post
test if the input is valid
retrieve current record
update values and save to DB */
if($form->isValid($this->getRequest()->getPost())){
$input=$form->getValues();
$client = Doctrine::getTable('PetManager_Model_Clients')
->find($input['clientid']);
$client->fromArray($input);
if($client->email=='')
{$client->email=NULL;}
if($client->mobile=='')
{$client->mobile=NULL;}
if($client->landLine=='')
{$client->landLine=NULL;}
if($client->address3=='')
{$client->address3=NULL;}
$client->save();
$sessionClient = new Zend_Session_Namespace('sessionClient');
$id = $client->clientid;
$fname = $client->firstName;
$lname = $client->lastName;
$sessionClient->clientid=$id;
$sessionClient->clientfName=$fname;
$sessionClient->clientlName=$lname;
$sessionClient->clientfName=$fname;
$this->_helper->getHelper('FlashMessenger')
->addMessage('The record for '.$fname.' '.$lname. ' was successfully updated.');
$this->_redirect('clients/client/success');
}else{
/* if GET request
set filters and validators for GET input
test if input is valid, retrieve requested
record and pree-populate the form */
$filters = array(
'id'=>array('HtmlEntities','StripTags','StringTrim')
);
$validators = array(
'id'=>array('NotEmpty','Int')
);
$input = new Zend_Filter_Input($filters,$validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$qry = Doctrine_Query::create()
->from('PetManager_Model_Clients c')
->leftJoin('c.PetManager_Model_Counties co')
->where('c.clientid=?',$input->id);
$result = $qry->fetchArray();
if(count($result)==1){
$this->view->form->populate($result[0]);
}else{
throw new Zend_Controller_Action_Exception('Page not found',404);
}
}else{
throw new Zend_Controller_Action_Exception('Invalid Input');
}
}
}
All help greatly appreciated.
Ok I've sorted this I stupidly left out a check in my update action to see if the request was being made by post as this is the action defined in my form.
The corrected code is shown below in case this helps anyone else.
// action to update an individual clients details
public function updateAction()
{
// generate input form
$form = new PetManager_Form_UpdateClient;
$this->view->form=$form;
/* if the requrest was made via post
test if the input is valid
retrieve current record
update values and save to DB */
if ($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())){
$input=$form->getValues();
$client = Doctrine::getTable('PetManager_Model_Clients')
->find($input['clientid']);
$client->fromArray($input);
if($client->email=='')
{$client->email=NULL;}
if($client->mobile=='')
{$client->mobile=NULL;}
if($client->landLine=='')
{$client->landLine=NULL;}
if($client->address3=='')
{$client->address3=NULL;}
$client->save();
$sessionClient = new Zend_Session_Namespace('sessionClient');
$id = $client->clientid;
$fname = $client->firstName;
$lname = $client->lastName;
$sessionClient->clientid=$id;
$sessionClient->clientfName=$fname;
$sessionClient->clientlName=$lname;
$sessionClient->clientfName=$fname;
$this->_helper->getHelper('FlashMessenger')
->addMessage('The record for '.$fname.' '.$lname. ' was successfully updated.');
$this->_redirect('clients/client/success');
}
}else{
/* if GET request
set filters and validators for GET input
test if input is valid, retrieve requested
record and pree-populate the form */
$filters = array(
'id'=>array('HtmlEntities','StripTags','StringTrim')
);
$validators = array(
'id'=>array('NotEmpty','Int')
);
$input = new Zend_Filter_Input($filters,$validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$qry = Doctrine_Query::create()
->from('PetManager_Model_Clients c')
->leftJoin('c.PetManager_Model_Counties co')
->where('c.clientID=?',$input->id);
$result = $qry->fetchArray();
if(count($result)==1){
$this->view->form->populate($result[0]);
}else{
$t=count($result);
throw new Zend_Controller_Action_Exception('Page not found',404);
}
}else{
throw new Zend_Controller_Action_Exception('Invalid Input');
}
}
}