codeigniter unsetting session works unexpectedly - php

I submit form to controller/complete action, set
$this->session->set_userdata('success', 3);
and then redirect to index action with redirect('controller', 'refresh');.
In my view I get
$success = $this->session->userdata('success');
do some work and then
$this->session->set_userdata('success', 0);
And it works fine, but when I reload page (it is an index action), I still get in $success 3, not 0. What am I missing?

I have seen many problems with codeigniter DB Session, and thus refuse to use it, to include the session not actually properly updating.
If you are interested I created a PHP Session based class that acts as a replacement, it benefits from backward compatability, but also a much easier way of using it.
Check out my Gist: https://gist.github.com/chazmead/1688becbcf11f897e962
To install you will need to replace the CI Session config in application/config/config.php to:
$config['session'] = (object)array(
'UID' => 'MY_SESSION_KEY',
'sess_expiration' => 7200,
'match_ip' => False,
'match_user_agent' => False
);
Then install the file to application/models/session.php
then instead of loading the CI session, just load this session model.
Using this is very easy, just assign variables to the session and it saves automatically, it also locks and unlocks the session so that async requests don't get locked up (which is a problem with PHP sessions)
For full backward compatability you may need to use $this->session = &$this->Session after loading the new model, otherwise you will have to make sure your calling session using Session (Uppercase S) as this is how CI models work. or install as a library instead..

The codeigniter by default managing session in COOKIE, more info
why the cookie value is not updated at once when i submit the form?
CI also provides setting to store session data in database table, if you store session in table this would work fine.
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html

Related

can't use session at codeIgniter

I have a session in my form controller the session is create when the user save
the session affect the form page so my problem is :
if I loaded the page without clicking on save a undefined index[session index] error appears
so I created the session at the home page
but the problem is if I loaded the form page without visiting the home page at first the undefined index error appear
I tried to call the method session_start() but I got this error
A PHP Error was encountered
Severity: Notice Message: A session had already been started -
ignoring session_start() Filename: views/Form.php Line Number: 5
I strongly recommend using the default CI session library. You can autoload the session in autoload.php. Your session will start automatically, there is no need to call session_start().
Then replace $_SESSION['save']="true" with $this->session->set_userdata('save', 'true');.
I think you need to check if session['save'] is true or not, so beforehand you must declare by default that session['save'] is "false" in the default controller which is specified in the routes.php, and also make sure the session['save'] index is already defined in your form page controller, check like this:
if ($this->session->userdata('save')) {
// do something when exist
} else {
$this->session->set_userdata('save', 'false');
}
I am not sure why you are trying to implement your own session management within CI as one of the powerful tools CI offers is a flexible, simple yet powerful session management system.
Even so, surely a simple solution to your conundrum is to simply check if the session variable is set or not in your form, and if it is not set then set it to a value of 0. In your controller, you can deal with that, i.e. check if the value is 0, and if so, start a session and assign the session variable, or throw the user out, or do whatever you need you app to do when the session is not found, or is set to 0 indicating a session has not been activated.
Your session will start automatically, there is no need to call session_start() in every controller. codeigniter session library takes care of it.
First you have to load session library. application/config/autoload.php
$this->load->library("session");
if you have loaded already no need of loading again.
To set data in session
$this->session->set_userdata("KEY","VALUE");
To get data from session
$this->session->userdata("KEY");

Codeigniter AJAX and Flashdata

How can I go about unsetting flashdata using the Codeigniter Session library? I know flashdata normally expires after one page refresh, however I'm using AJAX in a portion of my app, and when setting flash data, it still exists if I make a second AJAX call, so I need a method of unsetting flashdata manually.
I thought this might work as it is similar to unsetting session userdata:
$this->session->unset_flashdata('some_val');
However it doesn't do anything, any suggestions?
if you want to destroy all session value then use this:
$this->session->sess_destroy();
and if you want to destroy a particulat session the use:
$this->session->unset_flashdata('session name');
or
$sessionvar = $this->session->userdata('sessionname');
unset($sessionvar);
if this is not working then use following to empty the session value:
$this->session->set_flashdata("sessionname","");

Problems accessing same SESSION variables from different files

I'm developing a site using Wordpress.
My permalink structure is set to show post/page name. So accessing a page called store will look like this: www.mysite.com/store/?some=arguments
In all my WP templates, I'm able to output all my SESSION variables using print_r($_SESSION);
Doing the same from a file called from jQuery.ajax only outputs some of the SESSION varaibles.
I've used the following code to see if the cookie path is same for both files, and they are:
$sessCookie = ini_get('session.cookie_path');
echo 'session.cookie_path: '.$sessCookie;
I also have this code in my files to make sure session is started:
if (!session_id())
session_start();
Why am I not able to output the same session variables from a WP template and a php file called from jQuery.ajax?
UPDATE
jQuery.ajax calls jquery.php file. At the top of this file, it has the following code:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-blog-header.php');
This code fires functions.php. In this file I have the following code:
function session_manager() {
if (!session_id())
session_start();
// Get variables in query string
$_SESSION['action'] = (isset($_GET['action']) ? $_GET['action'] : '');
$user_geo_data = get_geoip_record();
$_SESSION['user_geo_location'] = get_object_vars($user_geo_data);
}
When functions.php is fired from jquery.php, it seems that session_id() returns false, thus I create a new session.
Is there a way to keep using the same session?
UPDATE 2
It seems that WP config kills all GLOBAL variables when initialized.
http://wordpress.org/support/topic/wp-blog-headerphp-killing-sessions
Wordpress can use its own session handler, and overrides the default session handler to do so. So in essence you've got two different sessions, even though they share the same ID. The cookie path is merely how the client-side cookie operates. What you need to check is session_save_path(), and check if WP is running sessions through the database instead of the default file handler.
The reason two sessions are fired up is because the first one is browser-based (through a cookie) and the second one, with Ajax, is essentially server-side and doesn't have access to the session cookie.
The session cookie is where the session ID is stored and is used to identify an existing session. A server-side Ajax script doesn't have access to the browser's cookies, thus fires up a new session.
It can be worse if the main script uses an alternate session "save handler" than the Ajax script, resulting in two separate sessions, stored in two different places.

Using PHP $_COOKIE to manage session vars

Due to server settings I am having to use $_COOKIE instead of $_SESSION to manage session vars for a project.
On my search form I set an initial cookie but am unclear whether this is helpful or needed?
setcookie('NOSG', 'oHai', time()+7200, '/', 'some.org');
Each time the search results page loads I iterate over the cookies and back date the ones I need to clear and then set the new values like so:
if ($board) {
foreach ($_COOKIE as $k => $v) {
if (preg_match('/boa_/', $k)) {
setcookie($k, '', time()-3600, '/', 'some.org');
}
}
foreach ($people as $p) {
setcookie('boa_'.$p->ID, $p->whatever, time()+7200, '/', 'some.org');
}
}
Mostly this is used for making sticky selections in multi-line <SELECT> inputs.
Is this approach sound? I have rarely used $_COOKIE for anything.
// EDIT 1:12 PM GMT-06:00
All of the comments and answers are focused on fixing sessions. I assume this is because there is some reason the method suggested is NOT sound? The question asked is about using $_COOKIE to remember form settings. Would anyone care to respond as to why the method I am using is or is not appropriate to the problem?
The error
Permission denied. session.save_path is set to /var/lib/php/session PHP Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0
Is due to an error on the part of your host/system administrator. They should set the permissions on /var/lib/php/session to 777 so it is writable by all users. If they are using something that executes your PHP script as your user, the data is still safe because your user will own the session data file so no one else can view or modify it.
Alternatively, you can change the session save path on the fly to a directory under your control.
If you were to have a common file that initiated your session, add this before session_start():
session_save_path('/home/yoursite/sessions');
// or
session_save_path($_SERVER['DOCUMENT_ROOT'] . '../sessions');
// or, an alternate method
ini_set('session.save_path', '/home/yoursite/sessions');
session_start();
Then just created that folder and set the permissions appropriately so it is readable/writable by your user only.
Technically all a session is, is a text file (OK, you can hold the data in a database as well) containing variables that's identified by a value held in a cookie (or the address bar).
It wouldn't be impossible to recreate the functionality within PHP using things like setcookie(), serialize() and file_put_contents() writing to a folder outside the web tree ... though you might also need a Cron job to schedule garbage collection (to be fair, PHPs native session GC doesn't seem to be spectacular).
You'd just need to create a custom session handling object and set the "session" id for it in a cookie exactly the same as if you were using normal session handling - except instead of using $_SESSION you'd use you Session::get() and Session::set() methods.
If you keep the API clean then, at a future date if you manage to get session handling enabled on the server, you'd only need to tweak your session handling object and it wouldn't affect the rest of your program code - it's probably a good idea to abstract away then session handling anyway.
None of the respondents addressed my question: Is using $_COOKIE to store session data a sound method?
Experience has taught me what they would not. Not all browsers handle cookies in the same way. For instance Internet Explorer has limits per domain on the number of cookies: http://support.microsoft.com/kb/941495
So the answer is- $_SESSION is superior to cookies as it is handled by PHP in the same manner for all browsers.

Find out if a session with a particular id has expired

I am creating an upload feature that stores a user uploaded file on the server with the user's session-id as its name. Now, I want to keep this file on the server only till that session is active.
So, my question is, how can I determine from the session-id, whether a session is active or expired so that in the later case I can safely delete the user uploaded file.
This I want to do as a cleanup at particular intervals maybe by using a cron job, though I have never used it before.
You can't just rely on session.gc_maxlifetime because after this time the session is marked as garbage and the garbage collector starts only with a probability of 1% by default ( session.gc_probability).
The better approach IMHO is to handle yourserlf the expired data.
You can for instance start the time and save it into a session variable:
<?php $_SESSION['last_seen'] = time();//Update this value on each user interaction. ?>
Later..via cron you can do something like this:
<?php
//Get the session id from file name and store it into the $sid variable;
session_id($sid);//try to resume the old session
session_start();
if (isset($_SESSION['last_seen']) && $_SESSION['last_seen'] > $timeout){//Session is expired
//delete file
session_destroy();
}else if (!isset($_SESSION['last_seen')){ //already garbaged
//delete file
session_destroy();
}
?>
Not tested...just an idea
I'm trying to do the exact same thing. One solution would be to define a custom garbage collector function with session_set_save_handler(). In this custom function you would delete the uploaded files associated with the session and then delete the session from disk. The only problem I see it's that you will have to define the rest of the session handlers as well:
bool session_set_save_handler ( callback $open,
callback $close,
callback $read,
callback $write,
callback $destroy,
callback $gc )
This is easy if you don't rely on PHP to handle sessions. Is there a way to call the default handler functions of PHP from a custom handler function?
Intervals can be made like this - someone opens your web -> php script is running -> it checks if files is time-outed -> delete time-oted files
And no CRON needed :-)
It is nearly impossible to determinate due to lack of information if user closed or not the browser window ( if he don't closes it but turn sleep mode on and come back in 2 days - session is still active AFAIK ) -
only idea to slove this problem in best manner this is to use own session engine with AJAX checking.

Categories