php - Session are lost after redirect in CodeIgniter 3
Asked Answered
A

10

11

I would like to have some help in CodeIgniter 3. Every time I login and redirect to the index page, session is lost.

Here is my code:

Controller:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Secretariat extends CI_Controller {
    public function __construct(){
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        $this->load->model('SecretariatModel');
        $this->load->model('IndiRegModel');
        $this->load->model('RoomModel');
        $this->load->model('BuildingModel');
        $this->load->model('BilletModel');
        $this->load->model('BatchRegModel');
        $this->load->library('form_validation');
        $this->load->library('session');
    }

    public function secretariatLogin(){

        if ($this->session->isSecretariat){
            redirect('secretariat/index', $data);


        } else{

            $data['title'] = 'PACSA - Philippine Association of Campus Student Adviser';

            $this->load->view('include/toppage', $data);
            $this->load->view('include/defaultnavbar', $data);
            $this->load->view('pacsa/slider');
            $this->load->view('secretariat/secretariatLogin', $data);
            $this->load->view('include/bottompage');

       }

    }

    public function signin(){
        $secretariat = array(
            'sec_email' => $this->input->post('sec_email'),
            'sec_password' => sha1($this->input->post('sec_password'))
        );

        $user = $this->SecretariatModel->getSecretariat($secretariat);
        //print_r($user->name);die();

        if(!$user == null){

            $newdata = array(
                'sec_id' => $user->sec_id,
                'sec_name'  => $user->sec_name,
                'sec_lastname' => $user->sec_lastname,
                'sec_email' => $user->sec_email,
                'sec_password' => $user->sec_password,
                'sec_status' => $user->sec_status,
                'sec_address' => $user->sec_address,
                'logged_in' => TRUE,
                'isSecretariat' => TRUE
            );

            $this->session->set_userdata($newdata);            
            redirect('secretariat/index');
        } else {
            $data['title'] = 'PACSA - Philippine Association of Campus Student Adviser';
            $data['message'] = 'Invalid email or password';

            $this->load->view('include/toppage', $data);
            $this->load->view('include/defaultnavbar', $data);
            $this->load->view('pacsa/slider');
            $this->load->view('secretariat/secretariatLogin', $data);
            $this->load->view('include/bottompage');
        }
    }    

    public function index(){
        $data['title'] = 'PACSA - Philippine Association of Campus Student Adviser';
        $id = $this->session->sec_id;
        var_dump($id);
        echo die();

        $this->load->view('include/toppage', $data);
        $this->load->view('include/secretariatnavbar', $data);
        $this->load->view('pacsa/slider');
        $this->load->view('secretariat/index', $data);
        $this->load->view('include/bottompage');
    }
}

So after redirecting to the index page, I want to verify if there is a session involved. I tried to echo the id and the name of the user but I get a null value.

Alliterate answered 28/1, 2018 at 10:1 Comment(2)
This kind of problem is often due to incorrect session and/or cookie configuration. Please show those $config settings.Escarole
stackoverflow.com/a/50792059Encephalogram
A
2

i just solved my problem turns out i have old version of codeigniter 3 i upgrade my CI to the latest version available on the website . thank you all for the help

Alliterate answered 31/1, 2018 at 10:36 Comment(0)
E
20

also check your php.ini file for this option:

session.auto_start=1
Elongation answered 28/1, 2018 at 10:25 Comment(5)
where can i locate the .ini file?Alliterate
what is your OS or server platform? Usually session problem occur when I running my web on localhost using XAMPP. The php.ini is in drive:/xampp/php/ or you can create a new .php file on your server, and write following code: <?php phpinfo(); ?> and open it from your browser, it will show all parameters of your server including your php configuration file (php.ini) locationElongation
Works for me. I thought the problem is in the framework! Thank you!Burning
Worked for me! The problem was with XAMPP on mac. By default it is set to session.auto_start=0Quest
I lost almost days and days to find as this simple and perfectly answer to Codeigniter Session problem! Thanks Sofyan!Rosenbaum
P
20

Go to

system/libraries/Session/session.php

at Line no 281 and replace

ini_set('session.name', $params['cookie_name']); 

by

ini_set('session.id', $params['cookie_name']);

This problem occurs normally while upgrading PHP later version to 7.3 +

Petrick answered 13/9, 2020 at 6:29 Comment(4)
Thanks man it's work for me you save my night <3 <3Sterling
if we do replacing that one for php 5.x is that okay?Distract
Yes, I don't think there should be any problem with the PHP version. Still, if you find any difficulties post it here.Petrick
You save my night!Entitle
K
2

Have you loaded your session library

this->load->library('session')

Or via autoload

$autoload['libraries'] = array('session');

Kuhl answered 28/1, 2018 at 10:8 Comment(5)
yes i have it loaded on my controller constructor and yes it also loaded in the autoload.phpAlliterate
@KyleCipriano You don't need to load it in your controller if it is loaded in your autoload.php fileSym
Codeigniter will automatically ignore it if its loadedKuhl
Are there any other libraries that you are using that are session related?Kuhl
no. just the session itself from the controller or from the autoloadAlliterate
A
2

i just solved my problem turns out i have old version of codeigniter 3 i upgrade my CI to the latest version available on the website . thank you all for the help

Alliterate answered 31/1, 2018 at 10:36 Comment(0)
G
1

Hope this helps, I'm working with Homestead - Vagrant - php7.4 and the only way I got it working was following this answer on Github

Add this in your

Project/application/config/config.php

 /* 
 |-------------------------------------------------------------------------- 
 | Cookie Related Variables 
 |-------------------------------------------------------------------------- 
 | 
 | 'cookie_prefix'   = Set a cookie name prefix if you need to avoid collisions 
 | 'cookie_domain'   = Set to .your-domain.com for site-wide cookies 
 | 'cookie_path'     = Typically will be a forward slash 
 | 'cookie_secure'   = Cookie will only be set if a secure HTTPS connection exists. 
 | 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) 
 | 
 | Note: These settings (with the exception of 'cookie_prefix' and 
 |       'cookie_httponly') will also affect sessions. 
 | 
 */ 
 $config['cookie_prefix']   = ''; 
 $config['cookie_domain']   = ''; 
 $config['cookie_path']     = '/'; 
 $config['cookie_secure']   = FALSE; 
 $config['cookie_httponly']     = FALSE; 

also change lines from 289 to 352 in your

Project/system/core/Input.php

/** 
 * Set cookie 
 * 
 * Accepts an arbitrary number of parameters (up to 7) or an associative 
 * array in the first parameter containing all the values. 
 * 
 * @param   string|mixed[]  $name       Cookie name or an array containing parameters 
 * @param   string      $value      Cookie value 
 * @param   int     $expire     Cookie expiration time in seconds 
 * @param   string      $domain     Cookie domain (e.g.: '.yourdomain.com') 
 * @param   string      $path       Cookie path (default: '/') 
 * @param   string      $prefix     Cookie name prefix 
 * @param   bool        $secure     Whether to only transfer cookies via SSL 
 * @param   bool        $httponly   Whether to only makes the cookie accessible via HTTP (no javascript) 
 * @return  void 
 */ 
public function set_cookie($name, $value = '', $expire = 0, $domain = '', $path = '/', $prefix = '', $secure = NULL, $httponly = NULL) 
{ 
    if (is_array($name)) 
    { 
        // always leave 'name' in last place, as the loop will break otherwise, due to $$item 
        foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'httponly', 'name') as $item) 
        { 
            if (isset($name[$item])) 
            { 
                $$item = $name[$item]; 
            } 
        } 
    } 
  
    if ($prefix === '' && config_item('cookie_prefix') !== '') 
    { 
        $prefix = config_item('cookie_prefix'); 
    } 
  
    if ($domain == '' && config_item('cookie_domain') != '') 
    { 
        $domain = config_item('cookie_domain'); 
    } 
  
    if ($path === '/' && config_item('cookie_path') !== '/') 
    { 
        $path = config_item('cookie_path'); 
    } 
  
    $secure = ($secure === NULL && config_item('cookie_secure') !== NULL) 
        ? (bool) config_item('cookie_secure') 
        : (bool) $secure; 
  
    $httponly = ($httponly === NULL && config_item('cookie_httponly') !== NULL) 
        ? (bool) config_item('cookie_httponly') 
        : (bool) $httponly; 
  
    if ( ! is_numeric($expire) OR $expire < 0) 
    { 
        $expire = 1; 
    } 
    else 
    { 
        $expire = ($expire > 0) ? time() + $expire : 0; 
    } 
  
    setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly); 
} 
Germicide answered 6/10, 2021 at 16:12 Comment(0)
B
1

I experienced this problem with the $config['sess_driver'] set to 'database'.

I was using a valid MySQL user so CodeIgniter 3 was not complaining about the sql connection but the user did not have all the right permissions to read/write from the table php_sessions (or the one set by $config['sess_save_path']).

In my case, I was using the default user 'debian-sys-maint' in my database.php.

Beaver answered 28/9, 2022 at 19:52 Comment(0)
S
0

Your problem doesn't come from the session itself.

Try to:

  • Comment the redirect method and add a var_dump($user) instead to see if your $user is correctly set. The problem could come from your $user object which contains null values for id and name.

  • Change if(!$user == null){ by if ($user != null) { or if ($user) {.

Sym answered 28/1, 2018 at 11:28 Comment(20)
Thank you. ok i tried to use var_dump on the $user and i got all the data from the user which i try to login then i did what you told me to change the if statement but when i use the var dump on the index to check if i get the id and name from the session, i still get NULL valueAlliterate
In your index method, can you tell me the result of var_dump($this->session->userdata())?Sym
hmmm i got this result array(1) { ["__ci_last_regenerate"]=> int(1517140453) }Alliterate
Comment the redirect('secretariat/index'); line again, and add this instead, just after set_userdata: var_dump($this->session->userdata());. What is the result here?Sym
i got this result array(10) { ["__ci_last_regenerate"]=> int(1517140803) ["sec_id"]=> string(1) "1" ["sec_name"]=> string(11) "Secretariat" ["sec_lastname"]=> string(9) "asdfghjkl" ["sec_email"]=> string(11) "secretariat" ["sec_password"]=> string(40) "92a87dfd4ec6c963caeb9e47ea97dd6f4f9c8441" ["sec_status"]=> string(6) "Single" ["sec_address"]=> string(10) "asdfghjkl;" ["logged_in"]=> bool(true) ["isSecretariat"]=> bool(true) } i got all the data from the user which i am trying to log inAlliterate
Which driver are you using to store your sessions? Look at Database Driver, and try again after you create the ci_sessions table and change your config file as it is said in the link below. Does it work?Sym
here's what i found on my config file : $config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = NULL; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE; should i set my 'sess_save_path' to ci_session? and my 'sess_driver' to database? will try this one thanksAlliterate
Yes you should try and create a new table in your database as it is explicated on the documentation link.Sym
when i set my 'sess_driver' to database am i going to literally put 'database' or am i going to put my database nameAlliterate
Only put the word "database"Sym
i got this error Severity: Warning Message: Use of undefined constant ci_sessions - assumed 'ci_sessions' (this will throw an Error in a future version of PHP) Filename: config/config.php Line Number: 373 Backtrace: File: C:\xampp\htdocs\pacsa\application\config\config.php Line: 373 Function: _error_handler File: C:\xampp\htdocs\pacsa\index.php Line: 316 Function: require_onceAlliterate
What did you do in your config file? Show me the line 373Sym
$config['sess_driver'] = 'database'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = ci_sessions; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE;Alliterate
Add quotes to ci_sessions: $config['sess_save_path'] = 'ci_sessions';Sym
ok i got rid of the error message but when i try to use var_dump on the index to check if i get the name and is from the session i dont have any output even the "NULL" data didn't showAlliterate
Did you try to login again?Sym
Add this in your index method: var_dump($this->session->userdata());, which result did you get?Sym
array(1) { ["__ci_last_regenerate"]=> int(1517145328) }Alliterate
Try to add this instead of the redirect method (comment it): $result = $this->session->set_userdata($newdata); var_dump($result);die;Sym
i just solved my problem turns out i have old version of codeigniter 3 i upgrade my CI to the latest version available on the website . thank you all for the helpAlliterate
S
0

If you are using PHP 7.1+/7.2 then this problem will happen. Change PHP version to down (to check if it works).

Solve answered 28/1, 2018 at 11:57 Comment(2)
I've used CodeIgniter 3 with PHP 7.2 and sessions worked fine. Your answer is not very helpful. Suggesting a different version of PHP doesn't solve anything.Avron
I have faced this issue with one of my application in localhost and also in live server then I changed PHP version now it works perfectly.Solve
M
0

We also get same issues. our spec : InvoicePlane, PHP 7.0, code igniter v.3.1.11. Every controllers which use redirect() helper got err_connection_refused from browser.

After spend hours exhaustive debugging. We solved this by change IP Address base_url to domain name and set certificate from letsencrypt.

Mindy answered 27/9, 2020 at 14:9 Comment(0)
K
-1

Try this

$this->output->profiler(true);

To see if session is really set and also check if the library is loaded

Kuhl answered 28/1, 2018 at 12:6 Comment(3)
sorry im kinda new to CI where will i put this line? ThanksAlliterate
In your controllerKuhl
It can be in the function you are calling or the contructor functionKuhl

© 2022 - 2024 — McMap. All rights reserved.