在CodeIgniter 3中重定向后会丢失php会话

11

我希望在CodeIgniter 3中得到一些帮助。每次登录并重定向到索引页面时,会丢失会话。

这是我的代码:

控制器:

<?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');
    }
}
所以在重定向到主页后,我想验证是否涉及会话。 我尝试回显用户的ID和名称,但我得到了一个空值。

因此,在重定向到主页后,我希望验证是否涉及到会话。我尝试打印用户的ID和姓名,但是我收到了一个null值。


这种问题通常是由于会话和/或cookie配置不正确引起的。请显示那些$config设置。 - DFriend
https://dev59.com/iGYq5IYBdhLWcg3wcwSE#50792059/ - General Grievance
10个回答

20

还要检查您的php.ini文件以获取此选项:

session.auto_start=1

我应该在哪里找到 .ini 文件? - Kyle Cipriano
你的操作系统或服务器平台是什么?通常在使用XAMPP在本地主机上运行我的网站时会出现会话问题。php.ini文件位于**drive:/xampp/php/**。或者您可以在服务器上创建一个新的**.php**文件,并编写以下代码:<?php phpinfo(); ?>然后从浏览器中打开它,它将显示您的服务器的所有参数,包括您的php配置文件(php.ini)位置。 - Sofyan Thayf
可以用。我以为问题出在框架上!谢谢! - Albert Israel
对我有用!问题出在我的Mac上的XAMPP。默认情况下,它设置为session.auto_start=0。 - CaptainZero
我花了几乎数天时间才找到这个简单而完美的Codeigniter会话问题的答案!感谢Sofyan! - MR.Internet

20

前往

system/libraries/Session/session.php

第281行并替换

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

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

在将PHP版本升级到7.3+时,通常会出现此问题。


1
谢谢,兄弟!这对我有用,你救了我的夜晚 <3 <3 - Muhammad Bilal
如果我们将其替换为PHP 5.x,那可以吗? - gumuruh
是的,我认为 PHP 版本不应该有任何问题。但如果您遇到任何困难,请在此处发布。 - Nikunj Dhimar
1
你救了我的夜晚! - Murilo L. Mattioli

2

您是否加载了会话库

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

或者通过自动加载

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


是的,我已经在我的控制器构造函数中加载了它,而且它也在autoload.php中加载了。 - Kyle Cipriano
@KyleCipriano 如果在您的autoload.php文件中加载了它,则无需在控制器中加载它。 - cusmar
Codeigniter会自动忽略它,如果它已经被加载。 - Ntiyiso Rikhotso
你是否使用了其他与会话相关的库? - Ntiyiso Rikhotso
仅从控制器或自动加载中返回会话本身,不要返回编号。 - Kyle Cipriano

2

我刚刚解决了我的问题,原来是因为我使用的是旧版本的CodeIgniter 3,我将CodeIgniter升级到了网站上最新的版本。非常感谢大家的帮助。


1

希望这可以帮到你,我正在使用Homestead - Vagrant - php7.4进行工作,唯一让它正常运行的方法是按照Github上这个答案的步骤进行操作。

将这段代码添加到你的文件中:

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; 

同时在你的代码中将289到352行进行修改

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

1
我遇到了一个问题,$config['sess_driver']设置为'database'。我使用了一个有效的MySQL用户,所以CodeIgniter 3没有抱怨sql连接,但是该用户没有从表php_sessions(或由$config['sess_save_path']设置的表)读/写的所有正确权限。
在我的情况下,我在database.php中使用了默认用户“debian-sys-maint”。

0

你的问题并不是来自于会话本身。

尝试:

  • 注释掉重定向方法,改为添加var_dump($user)以查看您的$user是否正确设置。问题可能来自于您的$user对象,其中包含idname的空值。

  • if(!$user == null){更改为if ($user != null) {if ($user) {


嗯,我得到了这个结果数组(1){["__ci_last_regenerate"]=> int(1517140453)} - Kyle Cipriano
请将 redirect('secretariat/index'); 这一行注释掉,并在 set_userdata 之后添加以下内容:var_dump($this->session->userdata());。这里的结果是什么? - cusmar
当我将我的'sess_driver'设置为数据库时,我是要字面上放置'database'还是要放置我的数据库名称? - Kyle Cipriano
我收到了这个错误:严重性:警告 消息:使用未定义的常量ci_sessions-假定为“ci_sessions”(在将来的PHP版本中,这将导致错误) 文件名:config/config.php 行号:373 回溯: 文件:C:\xampp\htdocs\pacsa\application\config\config.php 行:373 函数:_error_handler 文件:C:\xampp\htdocs\pacsa\index.php 行:316 函数:require_once - Kyle Cipriano
$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; - Kyle Cipriano
显示剩余15条评论

0
如果您正在使用PHP 7.1+/7.2,则会出现此问题。将PHP版本更改为较低版本(以检查是否有效)。

我使用了PHP 7.2的CodeIgniter 3,会话运行良好。你的回答并不是很有帮助。建议使用不同版本的PHP并不能解决任何问题。 - Brian Gottier
我曾在本地主机和实际服务器上遇到过这个问题,后来我更改了PHP版本,现在它可以完美运行。 - Prince John

0
我们也遇到了相同的问题。我们的规格:InvoicePlane、PHP 7.0、CodeIgniter v3.1.11。每个使用 redirect() 助手的控制器在浏览器中都会出现 err_connection_refused 错误。
经过数小时的详尽调试后,我们通过将 IP 地址 base_url 更改为域名,并设置来自 Let's Encrypt 的证书来解决了这个问题。

-1

试试这个

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

查看会话是否真的设置并检查库是否已加载


抱歉,我对CI还不太熟悉,这行代码应该放在哪里?谢谢。 - Kyle Cipriano
1
在你的控制器中 - Ntiyiso Rikhotso
1
它可以在你调用的函数中,也可以在构造函数中。 - Ntiyiso Rikhotso

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接