【问题标题】:Codeigniter check if LoggedIn in the index.php fileCodeigniter 检查 index.php 文件中是否有 LoggedIn
【发布时间】:2015-02-16 11:05:48
【问题描述】:

我真的需要帮助,我在 2 天前自己寻求解决方案,但没有结果。 我需要检查用户是否登录使用:

$CI =& get_instance(); $loggedIn = $CI->session->userdata('loggedin') == TRUE

如果 $loggedIn 为 true,则表示用户已登录。我需要在索引文件中检查这个,因为我从中选择了数据库:

$parsed = parse_url($_SERVER['REQUEST_URI']);
$path = $parsed['path'];
$path_parts = explode('/', $path);
$db = $path_parts[4]; 


if(isset($db) && is_numeric($db)){
    define('DB', $db);
}

$db 是我的数据库的名称,所以如果我在登录页面中,则没有问题,因为它是在 url 中设置和数字的。但是当我登录时,我将此 $db 存储在会话变量中,因此我需要进行此测试:

if($this->session->userdata('loggedin') == TRUE){
    define('DB', $this->session->userdata('db'));
}

我的数据库文件:

   $active_group = 'default';
   $active_record = TRUE;
   $db['default']['hostname'] = 'localhost';
   $db['default']['username'] = '*********';
   $db['default']['password'] = '*********';
   $db['default']['database'] = DB;
   $db['default']['dbdriver'] = 'mysql';
   $db['default']['dbprefix'] = '';
   $db['default']['pconnect'] = FALSE;
   $db['default']['db_debug'] = TRUE;
   $db['default']['cache_on'] = FALSE;
   $db['default']['cachedir'] = '';
   $db['default']['char_set'] = 'utf8';
   $db['default']['dbcollat'] = 'utf8_general_ci';
   $db['default']['swap_pre'] = '';
   $db['default']['autoinit'] = TRUE;
   $db['default']['stricton'] = TRUE;

平均问题是我需要通过 url 使用不同的数据库。如果用户输入此链接,例如:/user/login/34,他将使用名为 34 的数据库。

我正在使用 codeigniter php 框架 core/MY_Controller.php的代码

class MY_Controller extends CI_Controller
{
    public $data = array();
    function __construct ()
    {
        parent::__construct();

        $this->data['errors'] = array();
        $this->data['app_name'] = config_item('app_name');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->model('user_m');

        $db_prefix = 'autojahi_dev';
        $config = array(
           'hostname' => 'localhost',
           'username' => '****',
           'password' => '****',
           'database' => '****',
           'dbdriver' => 'mysql',
           'dbprefix' => '',
           'pconnect' => FALSE,
           'db_debug' => TRUE,
           'cache_on' => FALSE,
           'cachedir' => 'cache',
           'char_set' => 'utf8',
           'dbcollat' => 'utf8_general_ci',
           'swap_pre' => '',
           'autoinit' => TRUE,
           'stricton' => TRUE
        );

        if($this->uri->segment(4)){
               $config['database'] = $this->uri->segment(4);
        }          

      $this->load->database($config);
      //$this->db->reconnect();//shouldnt be required but try it if there is problem
      echo $this->db->database;//for testing 


        $current_link = uri_string();

        // Algorithm of autojahiz access autorization

        $allow_not_loggedin = array('login', 'logout', 'reset_pass', 'send_reset_pass_email', 'reset_pass_form', 'update_pass', 'views', 'invalid_link' );

        switch (strtolower( $this->router->class ) )
        {
            case 'user':
                $allow_loggedin = array('denied', 'index', 'edit', 'logout');
            break;

            case 'dashboard':
                $allow_loggedin = array('denied', 'index');
            break;
        }

        if ( $this->session->userdata('loggedin') == FALSE ) 
        {   
            if (!in_array( $this->router->method, $allow_not_loggedin) )
            {
                redirect( 'user/login' );
            }
        }
        else
        {   
            if (!in_array( $this->router->method, $allow_loggedin ) )
            {
                //redirect( 'user/denied' );
            }
        }
    }
}

【问题讨论】:

  • 我什么都不懂。根据用户,您将连接到不同的数据库?你有多少分贝?为什么在 index.php 中,您可以在配置文件中声明所有数据库,然后在模型的构造函数中选择您需要的数据库。
  • 我想通过 url 使用不同的数据库,例如对于这个 url : /user/login/56 系统必须使用名为 56 的数据库
  • 问题是我需要通过 url 使用不同的数据库。如果用户输入此链接,例如:/user/login/34,他将使用名为 34 的数据库。我无法找到解决此问题的方法
  • CodeIgniter 有 URI 助手,所以你不需要自己做解析。 CI 将更加健壮。你可以访问像$this->uri->segment(4);
  • @MikeMiller,因为 uri 库还没有加载!

标签: php mysql codeigniter


【解决方案1】:

在您的控制器中执行此操作。为方便起见,您可以在 application/core 文件夹中创建一个名为 MY_Controller.php 的扩展文件,并扩展到您的控制器,如

class Other_controller extends MY_Controller{}

在 application/core/MY_Controller.php 构造函数中做..

class MY_controller extends CI_Controller{

  public function __construct() {

   parent::__construct();

   $config = [
   'hostname' => '',
   'username' => '',
   'password' => '',
   'database' => 'defaultdb',
   'dbdriver' => 'sqlsrv',
   'dbprefix' => '',
   'pconnect' => TRUE,
   'db_debug' => TRUE,
   'cache_on' => FALSE,
   'cachedir' => APPPATH .'cache',
   'char_set' => 'utf8',
   'dbcollat' => 'utf8_general_ci',
   'swap_pre' => '',
   'autoinit' => TRUE,
   'stricton' => FALSE
  ];

  if($this->uri->segment(4)){
       $config['database']=$this->uri->segment(4);
  }          

  $this->load->database($config);

  $this->db->reconnect();//shouldnt be required but try it if there is problem

  echo $this->db->database;//for testing 

}

【讨论】:

  • 你让我在这里,但是为什么我在 MY_Controller 中使用它时会出错?我必须创建另一个控制器?
  • 你把 MY_Controller 放在 application/core 文件夹中了吗?
  • 我有一个问题,应用程序仍在使用 config/database.php 文件的配置
  • 关闭数据库自动加载。要检查您使用的是哪个数据库,只需 echo $this->database
  • 是的,我将 if 放在 core 文件夹中,现在当我将 $config = [ 替换为 $config = array( 但现在的问题是应用程序仍在使用 config 的配置时,它不会显示错误/database.php
【解决方案2】:

不确定这是否正是您所需要的,但我会这样做:

在 application/core 中,创建 MY_Loader.php

class MY_Loader extends CI_Loader
{

    public function database($params = '', $return = FALSE, $query_builder = NULL)
    {
        // Grab the super object
        $CI =& get_instance();
        $CI->load->library('session');

        $db_name = "mydefault_db";
        if($CI->session->userdata('db'))
            $db_name = $CI->session->userdata('db');

        $params['hostname'] = "localhost";
        $params['username'] = "root";
        $params['password'] = "";
        $params['database'] = $db_name;
        $params['dbdriver'] = "mysqli";
        $params['dbprefix'] = "";
        $params['pconnect'] = FALSE;
        $params['db_debug'] = TRUE;
        $params['cache_on'] = FALSE;
        $params['cachedir'] = "";
        $params['char_set'] = "utf8";
        $params['dbcollat'] = "utf8_general_ci";

        // Do we even need to load the database class?
        if ($return === FALSE && $query_builder === NULL && isset($CI->db) && is_object($CI->db) && ! empty($CI->db->conn_id))
        {
            return FALSE;
        }

        require_once(BASEPATH.'database/DB.php');
        if ($return === TRUE)
        {
            return DB($params, $query_builder);
        }

        // Initialize the db variable. Needed to prevent
        // reference errors with some configurations
        $CI->db = '';

        // Load the DB class
        $CI->db =& DB($params, $query_builder);
        return $this;
    }
}

然后在控制器中:

public function login($db_id)
{
    $this->session->set_userdata('db', $db_id);

    //Your stuff here

    //let's suppose we have a flag for the login success
    if(!$logedin)
        $this->session->unset_userdata('db');
}

【讨论】:

  • 谢谢,等一下,我现在就测试一下并发表评论。请稍等
  • 它显示错误:消息:未定义的属性:$CI->session->userdata('db') 行中的 User::$session
  • 会话库是否设置在自动加载中?
  • 是在自动加载中设置
  • 请在$CI =& get_instance();之后添加$CI->load->library('session');
【解决方案3】:

如果我是你,我将定义所有将使用的数据库,如下所示:

$db[30] = array(
    'hostname' => '',
    'username' => '',
    'password' => '',
    'database' => '',
    'dbdriver' => 'sqlsrv',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => APPPATH .'cache',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'autoinit' => TRUE,
    'stricton' => FALSE
);

$db[32] = array(
    'hostname' => '',
    'username' => '',
    'password' => '',
    'database' => '',
    'dbdriver' => 'pdo',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => APPPATH .'cache',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'autoinit' => TRUE,
    'stricton' => FALSE
);
$active_group = SELECTED_DB;

然后我将使用 Hook 来定义SELECTED_DB,或者在default_controller 中:

if($this->session->userdata('loggedin') == TRUE){
    define('SELECTED_DB', $this->session->userdata('selecdb'));
}
else{
   $selected_db = $this->uri->segment(2); // or use $this->input->get('db');
   $this->load->database($selected_db);
   defined('SELECTED_DB') 
      || define('SELECTED_DB', $selected_db);

   // Do login
}

【讨论】:

  • 我有超过 68 个数据库我无法在文件中定义它们,我发现的想法是当用户未登录时我从 $_GET ($this->uri ->segment),如果登录到数据库中,将从会话变量中选择
  • @AhmedFaiçal,当用户访问default_controller并且他没有登录时,你将他重定向到登录页面,对吗?那么你怎么知道使用哪个数据库呢?
  • 为什么不能在一个文件中定义68个数据库?
  • 我需要的是,我需要该用户通过 url 选择数据库。一旦选择。他可以访问该网站并登录 url 将是这样的 '/user/login/56' 56 是数据库的名称。我将从 url 检索并将其定义为全局变量“DB”,但问题是用户登录时。链接将被更改,我无法从 url 检索数据库,全局变量“DB”将为空
  • @MikeMiller 我无法定义 68 个数据库,因为我忽略了将来我将拥有多少数据库。我应该超过 600
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2022-01-23
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 2015-11-15
相关资源
最近更新 更多