Cannot get queued cookie from request - php

So I have PHP controller that sends cookie in queue, and I need to get this cookie next time when I refresh the page (and call this controller).
When controller is called, it checks if the cookie exists in request, an if not, it sets it in queue with expiration time 15 minutes.
But when this controller is called again, nothing is got in request. I've looked in dev-tools->Network->Cookies and haven't found this cookie neither in Request nor in Response section. At the same time, getQueuedQookies() shows that this cookie has been added to the queue. The code looks as follows:
$cookie = $this->request->cookie('id');
if($cookie=='id') {
die('ID detected.');
} else {
$this->cookieJar->queue('id', 'id', 15);
}
Then other actions are taken, and the controller returns some string in the end.
What am I doing wrong and how can my problem be solved? Would highly appreciate any possible help!

Update
change test to your function name and CookieJar will be auto injected.
public function test(CookieJar $cookieJar, Request $request){
$cookie= $request->cookie('id');
if($cookie=='id') {
print('ID detected.');
} else {
$cookieJar->queue(cookie('id', 'id', 15));
}
}

Related

yii Session gets cleaned on every request

Example of my code:
class SiteController extends Controller {
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex() {
$_SESSION['test'] = 'testdata';
var_dump($_SESSION); exit;
}
Example on the second request:
class SiteController extends Controller {
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex() {
var_dump($_SESSION);exit;
}
I have a project in yii. Project not mine - I'm just trying to fix errors.
My problem is:
first var_dump() shows that $_SESSION variable HAS the "test" index with "testdata". On the second request though I get an empty array of $_SESSION variable. Meaning, that every request session gets cleaned up. I've checked - the session ID stays the same. I've also checked this projects config - i can't find any references to extending SESSION component and changing it's behaviors. Also, when logging in yii DOES save states into SESSION, but the login fails because of SESSION being cleaned after redirect. That is to say COOKIE BASED authentication works which just proves the root of the problem.
Would very much appreciate help.
UPDATE
I've narrowed it down. This is the code for FRONT YII FRONT CONTROLLER(index.php):
<?php
#session_start(); // this line is at cwebuser.php at init() method and it is called at every request. should work properly.
var_dump($_SESSION);
$_SESSION['test'] = 'asdasd';
var_dump($_SESSION);exit;
It still prints empty $_SESSION on the second REQUEST. So the problem is probably not with the framework.
You can set session details in your /protected/config/main.php (this is the default unless you have changed it in index.html)
'session' => array(
'autostart' => true,
'timeout' => 1440, // time in seconds
),
Read about Session on CHttpSession
My problem was that I accessed my website via server ip : 123.123.123.123/site/index and this has conflicts with accessing and saving the session. Though I don't know the details. If someone has knowledge on this stuff I will gladly accept his(her) answer as the right one.
There is a file called controller.php under protected/components/controller.php which will be called before any action get called .. u can check that file and see... is there done any logout function calledthere...
//It clears all the sesstion data... or any php way
Yii::app()->user->logout();
Yes if u are in moule then u can also check ModuleName.php under module directopry ... if there is any session clearing script...
which clears the session... And yes this is not the right way of using session in Yii yes it is PHP but YII .... u can use folowing sytax dfor sessions..
//to set a session variable mnamed test
Yii::app()->user->setState('test',$test);
//to get a session variable named tets
Yii::app()->user->getState('test');

Laravel session data not sticking across page loads

I tried running the following code:
Session::put('progress', '5%');
dd(Session::get('progress'));
This will show '5%' in the dump.
If I rerun the same page but comment out Session::put('progress', '5%'); so that only the dd() line is called, I get a null value instead of the 5% values stored in the previous page load.
Here is my sessions config, so I know it should be storing the data:
'driver' => 'native',
'lifetime' => 120,
'expire_on_close' => false,
Why is Laravel not storing the session data across page loads?
The problem is because you are killing the script before Laravel finishes its application lifecycle, so the values put in session (but not yet stored) got killed too.
When a Laravel application lifecycle starts, any value put in Session are not yet stored until the application lifecycle ends. That is when any value put in Session will be finally/really stored.
If you check the source you will find the same aforementioned behavior:
public function put($key, $value)
{
$all = $this->all();
array_set($all, $key, $value);
$this->replace($all);
}
If you want to test it, do the following:
Store a value in session without killing the script.
Route::get('test', function() {
Session::put('progress', '5%');
// dd(Session::get('progress'));
});
Retrieve the value already stored:
Route::get('test', function() {
// Session::put('progress', '5%');
dd(Session::get('progress'));
});
Rubens Mariuzzo's answer is very good. I just want to add that if you need the data to be stored immediately you could use the save method:
Session::put('progress', '5%');
Session::save();
For me, even after data has been stored to session properly:
dd(Session::all());
returns nothing, but:
print_r(Session::all());
returns all session data!
In my case I flashed the variable in one request and then put it into session in another request (with the same name).
Unfortunatelly, terminating method went through all the previously flashed properties and cleaned my newly created session property (it was flushed in previous request so laravel thought it was no longer required and couldn't tell it was newly created). I figured it out debugging Kernel->terminateMiddleware method. You can put a breakpoint in terminating method. At some stage it reaches Store->ageFlashData. This is the method responsible for deleting my property.
I moved the session middleware
\Illuminate\Session\Middleware\StartSession::class
to the property $middleware in
app/Http/Kernel.php
In this case, you need to remove it from the web group ($middlewareGroups)
It helped me, I hope it helps you too

Does PHP's Laravel 4 hit the Database on every call to the Auth class?

I am building my first Laravel 4 Application (PHP).
I find myself needing to call somthing like this often in most of my Models and Controllers...
$this->user = Auth::user();
So my question is, is calling this several times in the application, hitting the Database several times, or is it smart enough to cache it somewhere for the remainder of the request/page build?
Or do I need to do it differently myself? I glanced over the Auth class but didnt have time to inspect every file (16 files for Auth)
Here is the code for the method Auth::user().
// vendor/laravel/framework/src/Illuminate/Auth/Guard.php
/**
* Get the currently authenticated user.
*
* #return \Illuminate\Auth\UserInterface|null
*/
public function user()
{
if ($this->loggedOut) return;
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method becaue that would tremendously slow the app.
if ( ! is_null($this->user))
{
return $this->user;
}
$id = $this->session->get($this->getName());
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if ( ! is_null($id))
{
$user = $this->provider->retrieveByID($id);
}
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->getRecaller();
if (is_null($user) and ! is_null($recaller))
{
$user = $this->provider->retrieveByID($recaller);
}
return $this->user = $user;
}
To me, it looks like it will get the user from the database only once per request. So, you can call it as many times as you want. It will only hit the DB once.
Auth::user() only hits the DB once, so it's not a problem invokes it many times. Btw, you can cache useful information of the user that you want to access frequently.

Symfony Session Last Request Time

Is it possible to make an action (more specifically 'ajax/heartbeat') not update last request time for the session ?
It is used for fetching notifications etc, so it shouldn't update timeout on sessions or they will never expire.
If the user is doing stuff on the page (onmousemove) I set update=true else update=false
Well, you will have to hook into the User lib of Symfony.
lastRequest is updated during the initialization of the User lib (ie: inside sfBasicSecurityUser).
Inside your app/[appname]/lib/myUser.class.php, extends this initialize function to not set the request time. Something ugly like that:
public function initialize(sfEventDispatcher $dispatcher, sfStorage $storage, $options = array())
{
$lastRequest = $this->getLastRequestTime();
parent::initialize($dispatcher, $storage, $options);
if (condition)
{
$this->lastRequest = $lastRequest;
}
}
The only things you need to find is, how to catch the module/action from the myUser lib and then place it in condition.

Zend_Session: determine if Session was initially started or just updated

I've got a problem with Zend_Session. I need to know, if the Session for this user was initially started the first time or if it was just updated in the current request.
I need to know that for statistics. If the session was initialized (meaning the user visits my app for the first time) I want to store the referer of the request in some db-table. This of course I only want to do for the first request within this session.
The manual talks about the methods Zend_Session::isStarted() and Zend_Session::sessionExists(). But it seems that both methods only work for within the current request (meaning it returns true if I use Zend_Session::start() somewhere in my app).
My approach was the following:
I tried to override Zend_Session::start() to insert the statistic-data into my db-table.
// Somewhere in my bootstrap:
My_Session::start();
// This is my class (eased up)
class My_Session extends Zend_Session
{
public static function start($options)
{
parent::start($options);
if(/* Here I need the condition to test, if it was the initial session-starting... */)
{
$table = new Zend_Db_Table(array('name' => 'referer'));
$row = $table->createRow();
$row->url = $_SERVER['HTTP_REFERRER'];
$row->ip = $_SERVER['REMOTE_ADDR'];
// ... some columns ...
$row->save();
}
}
}
Anybody has any idea?
I need to know, if the Session for this user was initially started the first time or if it was just updated in the current request.
Not a problem:
Zend_Session::start();
$my_logger = new Zend_Session_Namespace('my_logger');
if(isset($my_logger->has_already_visited_app) && $my_logger->has_already_visited_app) {
// this is not the first request
} else {
// this is the first request, do something here
// make sure to add the following
$my_logger->has_already_visited_app = true;
}

Categories