CodeIgniter: checking if user logged in for multiple pages

Делание "переименовывает asp к aspx и изменению, пока это не компилирует" порт приложения на asp.net, я сказал бы, что даже классик asp стиль программирование в.NET лучше, чем классик asp. VS, конечно, поощрит Вас попадать в яму успеха и управлять Вами к веб-формам и коду - позади способа сделать вещи, но язык достаточно выразителен для тиражирования шаблонов классика asp (а именно, много золотых самородков/встроенного кода, страниц перекрестной рассылки, и т.д.)

я думаю, что услышал, что это сказало прежде, что можно записать КОБОЛ на любом языке. Это правда для классического asp.

22
задан webvitaly 4 December 2015 в 16:52
поделиться

1 ответ

Для codeIgniter 3 я изменил ответ Уэсли Мерча на это

// Создать файл application / core / MY_Controller.php

<?php 
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {

function __construct()
{
    parent::__construct();
    $CI = & get_instance();
    $CI->load->library('session');
    $CI->load->helper('url');
    if ( !$this->session->userdata('logged_in'))
    { 
        redirect('login');
    }
}

}

Затем в любом контроллере для проверки авторизации я использовал

класс News extends MY_Controller {// code here}

Если вы используете модули и разные сеансы для пользователей сайта и пользователи-администраторы, вы можете использовать этот код для идеального перенаправления их на разные страницы входа в систему -

function __construct() {
    parent::__construct();
    $CI = & get_instance();
    $CI->load->library('session');
    $CI->load->helper('url');
   // echo "<pre>";print_r($this->router);echo "</pre>";

    /**
     * if webmaster then check admin session else check user session
     * But there may be some classes's method that doesn't requires login hence it is also need to check if
     * current request is for those methods before checking session
     */
    //to use $this->config->item('webmaster_name') this you have to define 
    // $config['webmaster_name'] = "webmaster"; in config.php file

    if ($this->router->module == $this->config->item('webmaster_name')) {
        if (!$this->session->userdata('admin')['id']) {
            redirect($this->config->item('webmaster_name').'/login');
        }
    } else {
        if (!$this->session->userdata('user')['id']) {
            redirect('login');
        }
    }
}

Если вы также хотите, чтобы пользователи разрешали доступ к некоторым методам с любого конкретного контроллера без входа в систему, вы можете использовать этот код -

function __construct() {
    parent::__construct();
    $CI = & get_instance();
    $CI->load->library('session');
    $CI->load->helper('url');

    //echo "<pre>"; print_r($this->router);echo "</pre>"; //_pr($this->config->item('excluded_auth'));
    /**
     * if webmaster then check admin session else check user session
     * But there may be some classes's method that doesn't requires login hence it is also need to check if
     * current request is for those methods before checking session
     */
    if ($this->router->module == $this->config->item('webmaster_name')) {
        if (!$this->session->userdata('admin')['id']) {
            redirect($this->config->item('webmaster_name') . '/login');
        }
    } else {
        if (array_key_exists($this->router->class, $this->config->item('exclude_auth')) && in_array($this->router->method, $this->config->item('exclude_auth')[$this->router->class])) {
            //echo "escape this method. don not validate for a session";
        } else {
            if (!$this->session->userdata('user')['id']) {
                redirect('login');
            }
        }
    }
}

Примечание: Вы можете определить пользовательский файл конфигурации для определения исключенных методов, таких как as-

//save file in application/config/without_auth_methods.php

<?php
     defined('BASEPATH') OR exit('No direct script access allowed');
     $config['exclude_auth']['news']       = array('index', 'view');
     $config['exclude_auth']['users']      = array('index');
5
ответ дан 29 November 2019 в 04:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: