Strange behavior of Codeigniter session - php

I am working on an application built on CodeIgniter. This application extends its controllers using a custom controller CP_Controller which lives in application/core. It looks like this:
class CP_Controller extends CI_Controller {
var $settings;
var $body_classes = array();
var $data = array('theme' => 'cmodule');
public function __construct() {
parent::__construct();
// print_r($_SESSION);
}
...
}
The problem is, print_r($_SESSION);. If I uncomment it, it prints [__ci_last_regenerate] => 1589186369. That's fine. No custom session data.
But for a particular request only, this returns a whole array filled up with session stuff. Even if it is the only request I run in a brand new browser session or private mode.
In this scenario, what's stranger is that business logic has not yet reached execution and no sessions have been set before this point. Then how's it possible that at this point, in a blank browser session, I am getting session data. I am not able to figure out the origin of this session data, where is it being set into the session? It only calls parent::__construct(); before print_r.
Is there really any way a Codeigniter application can hook into session and populate a session at a very initial system bootstrap level (for that particular request only)? Or there could be any other way?
Thanks.

Related

code igniter 4, csrf problem after echo view and exit

my main purpose to include some pagedata on BaseController, To do so, i decided to put a protected function under basecontroller and i used it to display pages ( instead of return view('page') );
example of my code,
Under BaseController
protected function display($page = NULL,$data = NULL){
global $settings;
$general_data = array(
'activeGoogleAnalytics' => $settings['activeGoogleAnalytics']
);
$data = array_merge($data,$general_data);
echo view($page,$data);
exit; // if exit is removed, csrf error is not appear, else there is csrf error while submitting forms
}
Then, i use display function as follows in my controllers,
public function index()
{
//get some data
$this->display('login/index',array(
'someData' => '$someData',
));
}
This is actually working fine, i am merging two different arrays, and some content which are same in all pages are assigned to data array from BaseController.
My problem is whenever i submit form, i get csrf error "You cannot Perform this action". Even if i remove csrf protection from forms i got this error.
I found solution to the problem, by removing exit; from display function. But i am not sure what causes this problem or it is right decision. Because codeigniter is a framework, there should be better way of assigning page data ( which is same in all pages like website settings ).
Without using exit after echo, probably i ll face with AJAX problems in the future. Hence, i want to keep exit, or i want to learn easy way of assigning some data to view 's array from BaseController for all pages.

How can i set a global variable value in one function and access it through another in codeigniter?

I'm currently creating an app with Codeigniter and i came up with this issue (and it's not the first time to be honest).
What i want is to set a value in a global variable in function "foo()" and the access it through function "bar" (which is called through ajax call from client side).
In short, i want this variable to be full when the user has visited the page (sth like a session).
Here's an example code of my controller and what i'm trying to achieve:
class Groups extends CI_Controller{
private $page_id;
public function foo($slug = FALSE){
$this->load->model('some_model');
$info = $this->some_model->get_info($slug);
$this->page_id = $info['page_id'];
}
public function bar(){
$this->load->model('some_model');
$info = $this->some_model->get_some_other_info($this->page_id);
//Some code in here
}
}
Any suggestions or best practices on achieve that?
I've tried searching the internet on that but i couldn't find something to start with. So if you have any suggestions on where to look at, feel free to do it!
Thanks
If i understand it right you will have 2 calls. One will be at page load where you want to store something and after that there will be an ajax call that will retrieve what you have stored. Because the 2 script loads are different you can only do it by storing the data to one of them: database/session/cookie/html session or localstorage.
Can't say anything about best practice because i dont know what you want to store and for how long so need a bit more info about your code (im guessing you want to store the "page_id"?).

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

Cannot expire cookie from a controller in CakePHP 2.x

I am building an API in CakePHP. I have a function that as part of its execution first destroys the cookies associated with the session. I am using the following code to do this.
public function new_thing () {
// I first call another controller to use functions from that controller
App::import('Controller', 'Person');
$PersonsController = new PersonsController;
// This function call is the problem
// This does not throw any errors but does not destroy the cookie as requested
$PersonsController->_kill_auth_cookie()
}
// This is from the Person controller, these are the functions used in the API
// This is the function that sets the cookies
public function _set_auth_cookie( $email ) {
setcookie(Configure::read('auth_cookie_name'), $email);
}
// this is the function that does not properly destroy the cookie from the API
// interestingly, it does work when called from in this controller
public function _kill_auth_cookie() {
setcookie(Configure::read('auth_cookie_name'), 'xxx', time()-7200);
}
I cannot get the API to properly expire the cookie that is created earlier in the session, I am not sure why. Additionally—what is maddening—is that the logs are empty and no error is being thrown of any kind, so I am not sure what to do next.
There is so much wrong in this code and concept…
DON'T instantiate controllers anywhere. It is plain wrong, broken by design and violates the MVC pattern. Only one controller should be dispatched by the framework itself based on the request; you don’t instantiate them manually.
An API using cookies? Well, not impossible but definitely not nice to work with. It’s possible but I’ve never seen one in the wild. I feel sorry for the person who has to implement it. See this question.
Why are you not using the CookieComponent? It has a built-in destroy() method to remove a cookie.
If you have an “auth” cookie, why are you not using CakePHP’s built-in Auth system? It will deal with all of that.
Use App::uses() not App::import() here
By convention, only protected functions should be prefixed with _
The first point is very likely the reason why cookie and sessions are messed up because the second controller instance initiates components again, and by this cookie and session maybe a second time as well. However, this can lead to “interesting” side effects.
I first call another controller to use functions from that controller
This is the evidence that your architecture is broken by design. The code that needs to be executed somewhere else; should be in a model method in this case. Or at least a component if there are controller-related things to be shared between different controllers.

Symfony Session Values Lost

I'm experiencing a problem with symfony's session values handling.
Basically, the problem is this, I have a action filter activated that takes the values of the module and action executed and stores them in the session superglobal.
This is my filter's code:
<------BEGIN CODE---------------->
class getPrevModuleActionFilter extends sfFilter
{
public function execute ($filterChain)
{
//---------------Code to execute *BEFORE THE ACTION* execution---------------
if ($this->isFirstCall()) # Execute this filter only once
{
// Filters don't have direct access to request & user objects => Use context object to get them
$request = $this->getContext()->getRequest();
$user = $this->getContext()->getUser();
if($request->getParameter('action') !== "setCulture")
{
$_SESSION['prev_module'] = "M=".$request->getParameter('module');
$_SESSION['prev_action'] = "A=".$request->getParameter('action');
}
}
//---------------Execute next filter in the chain---------------
$filterChain->execute();
//---------------Code to execute *AFTER THE ACTION* execution, before the rendering---------------
//(...)
}
}
<------END CODE---------------->
The weird thing is that if I do a print_r on the front web controller at the very last minute I see that:
When an action that's not 'setCulture' all goes well (ie, the session gets previous module and action as it should)
When action 'setCulture' gets executed: Symfony stores following values in session:
Array (
[prev_module] => M=
[prev_action] => A=
(etc)
)
ie, it looses the values of session for those 2 entries.
I tried using different namespaces, I tried using symfony's setAttribute from sfUser to handle session values. At the end I tried the raw session handling of PHP. Apparently it seems that the shutdown methods of the factories related to user and storage of session values mess up the session values!
I need your help, please.
SPECS:
Symfony version: 1.4.6
PHP: 5.3
I have Symfony's cache disabled
I'm running the code with the frontend_dev.php controller
Well, I guess Symfony messes up SESSION and COOKIES when used in filters.
I ended up creating my own filter mechanism that performs actions for an entire app.
So, to clarify, my choice was:
create a class autoloaded in root lib folder, that has a static method called 'fe_app_init'
add a preExecute method to the actions of each module in FE app that uses fe_app_init from that class
Now the fe_app_init() handles the values in SESSION rightfully.
It's a shame that Symfony 1.4 has a tool such as filters but then messes up SESSION and COOKIES handling in those.

Categories