Session data gone after redirect in CI - codeigniter

i need your help.
I used the session to record the user selected business type in CI. For example,$this->ci->session->set_userdata('biztype','food'). When user login,it works ok. However, once the user logout, session will be destroyed in the function logout().So i set the userdata again in the function logout().You can view the code below:
function logout()
{
$biztype = $this->ci->session->userdata('biztype');
$this->delete_autologin();
$this->ci->session->set_userdata(array('user_id' => '', 'username' => '', 'status' => ''));
$this->ci->session->sess_destroy();
$this->ci->session->set_userdata('biztype',$biztype);
//echo $this->ci->session->userdata('biztype'); //here, i can get biztype that i want
}
However,when i logout and redirect to homepage, i cant get the userdata('biztype') and my session_id have changed.
Thanks for the help.

This is straight from CodeIgniter User Guide:
Destroying a Session
To clear the current session:
$this->session->sess_destroy();
Note: This function should be the last one called, and even flash
variables will no longer be available. If you only want some items
destroyed and not all, use unset_userdata().
So no, you cannot destroy a session then add user_data to it, you need to reload / redirect then once the NEW session is established add data.
Try using cookies for peristance, or use the mentioned unset_userdata() fn.

$this->session->sess_destroy() ;
This function should be called only at the end of the execution. For unsetting data (as you're trying to do) it's better to use unset_userdata method. See how you should implement that:
$unset_items = array('user_id' => '', 'username' => '', 'status' => '') ;
$this->ci->session->unset_userdata( $unset_items ) ;

$email = "abc#gmail.com";
///set the session
use the set_userdata function and include the session library
$this->load->library('session');
$this->session->set_userdata('session name',Value);
i.e.
$this->session->set_userdata('email', $email);
//unset the session
$this->session->unset_userdata('session name');
i.e.
$this->session->unset_userdata('email');

Related

The sessions are dying on redirect

The sessions are no longer working on redirect, if i set a session with session([ 'key' => 'value' ]); is working on the same page, but if i set the session in controller, after redirect is NULL, also, when i redirect, the values passed ->with(array) are NULL:
return redirect()->route('account.login', ['subdomain' => 'account'])->with(
[
'request-tfa' => true,
'requested-email' => $validatedData['email'],
'requested-password' => encrypt($validatedData['password'])
]);
When i get the value using Session::get('request-tfa') is NULL, until now, this worked perfectly.
Do anyone have any idea how to fix it?
Should i try to use a database as session storage? but i don't know how to setup the database to store the sessions.
EDIT: I changed the session driver to database and is still not working, but the sessions are stored.
And even \Auth::attempt is not working, like, if i use:
if(\Auth::attempt(['email' => $validatedData['email'], 'password' => $validatedData['password']]))
{
return \Auth::id();
}
it working, but if i have return redirect i am guest again.
EDIT X2
Well, i changed my virtual host domain and restarted my pc and now is working...
If you want to have a session after redirect you should use:
session()->put('something')

Testing setting she session used in the intended()-method in Laravel

Laravel has a intended()-method used for redirecting users after a login. It uses the session key url.intended, as seen here. However, when testing it, doesn't seem to work. I set the session like this: session(['url.intended' => url()->previous()]);
Then this is how I test the session:
$this->app['session']->setPreviousUrl('some-url');
$response = $this->get(route('login'));
$response->assertSuccessful();
$response->assertSessionHas('url', 'some-url'); //fails
$response->assertSessionHas(['url' => ['intended' => 'some-url']]); //fails
When not using dot-notation as key, it works. Meaning, I can assert a session with key urlIntended exists.
How do I go about this?
I just realized that using the intended()-method actually returns AND removes the session since it is using pull().
Here is how it is used more specifically: $path = $this->session->pull('url.intended', $default);

fatfree sessions, different values in database and echo stmt

I have this in my beforeroute() of a controller
public function beforeroute()
{
new \DB\SQL\Session($this->db);
$mapper = new \DB\SQL\Mapper($this->db, 'users');
$auth = new \Auth($mapper, array(
'id' => 'username',
'pw' => 'password'
));
if (!$auth->login('validuser', '1234')) {
die('username or password wrong');
} else {
echo ($csrf = $this->db->exec('SELECT csrf FROM sessions')[0]['csrf']);
}
}
After I hit the page, I have different values for csrf in database and what's been echoed out on page. Why is that?
The csrf token is renewed on every request. You see different values on the page and in the database, because the value in the database was updated after your page has rendered.
To be more specific, the SQL Session handler replaces the default php session handler, and that's why the call to session_commit within the unload method https://github.com/bcosca/fatfree-core/blob/master/base.php#L1903 (is called when the framework shut down) will update your session database table with the new value.
To have a way to reuse that single csrf token for your purpose, just put it back into the session itself:
$s = new \DB\SQL\Session($f3->get('DB'));
// old value from last request
echo $f3->get('SESSION.csrf');
// remember current value for next request
$f3->set('SESSION.csrf',$s->csrf());
Maybe there`s an easier way, but I haven't figured it out yet.

Facebook losing logged in user with ajax

I am writing a Facebook app and have used the Facebook php SDK so it can be authorized server side. I can see this is working because after authorization when Facebook redirects back to my app, I have the following code in my index.php...
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '111111111111111',
'secret' => '11111111111111111111111111111111',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
...and $user returns not null. So far, so good!
I have a link on my app that loads content via ajax when clicked. Here's the JS:
$.post('my_content.php', {
action: 'render'
}, function(res){
if (res.html.length) {
$('.content').html(res.html);
}
},'json');
The problem is, the my_content.php script seems to be losing the fact the user has logged in and authorized the app.
The code I run in the my_content.php script to check whether the user is logged in is the same as in index.php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '111111111111111',
'secret' => '11111111111111111111111111111111',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
This time though $user = $facebook->getUser() returns null.
Is there a way to check if the user is logged in and authorized when running a PHP script with an AJAX call?
Should I store something in a session variable in my index.php script?
EDIT
After even more reading, I'm wondering if I need to retrieve the access token using the JavaScript SDK and pass it to my_content.php. Does anyone know if that's the correct way to do it?
EDIT 2
Turns out the line giving me the problem isn't $user = $facebook->getUser():
It is this one
$user_profile = $facebook->api('/me');
This line fails with the error 'OAuthException: An active access token must be used to query information about the current user.'
Strangely though, if I do this
$access_token = $facebook->getAccessToken();
$user = $facebook->getUser();
echo $access_token;
echo $user;
I do indeed have an access token and a user ID, so it looks like it may well be the bug reported by CBroe - check comments below.

remember me functionality in codeigniter

I have implemented remember me functionality as this question
How to create "remember me checkbox" using Codeigniter session library?
first answer.
I created a cookie with a random number code as value and it stored in db(user table). On login, db code checks with cookie value.It works fine on my localhost server. But in live server which has a subdomain url has problem.Also I tested it with another server with ip address as url. There also it is not working. In both cases cookie created but cant read the cookie. Please help me.
cookie set by
$auto_login_hash_code = uniqid();
$domain = $_SERVER['SERVER_NAME'];
$cookie = array(
'name' => 'rememberMe',
'value' => $auto_login_hash_code,
'expire' => 31536000,
'domain' => $domain,
'path' => '/'
);
$this->input->set_cookie($cookie);
and reading cookie by
if (get_cookie('rememberMe')) {
$hashcode = $this->CI->input->cookie('rememberMe');
$this->CI->load->model('loginmodel', '', true);
$username = $this->CI->loginmodel->get_username_by_hashcode($hashcode);//in this function setting session variables
}
Thanks in advance
iijb
you are getting library for that on github.
search remember me on github, load it and just follow below steps.
Verify cookie if token is present in database go to home page
$this->load->library('rememberme');
$cookie_user = $this->rememberme->verifyCookie();
if ($cookie_user)
{
$this->load->view('search_view');
}
else
{
// If checkbox is checked it return true either false
$checked = (isset($_POST['Checkbox1']))?true:false;
if($checked== true)
{
//$this->load->view('tested');
$this->load->library('rememberme');
$this->rememberme->setCookie($this->input->post('loginemil'));
//$this->rememberme->setCookie('set cookie here');
}
else{
dont set anything
}
}
Also this can be done by editing/extending system Session library.
First: In user login function add remember me check-
if($remember)
{
$data['new_expiration'] = 60*60*24*30;//30 days
$this->session->sess_expiration = $data['new_expiration'];
}
$this->session->set_userdata($data);
Second: Edit system Session library [I am not sure whether extending Session will work or not]
Go to this line in sess_read() method
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
Before that line add following code
if(isset($session['new_expiration'])){
$this->sess_expiration = $session['new_expiration'];
}
This works fine for me.

Resources