creating back page links in Codeigniter

后端 未结 5 1753
眼角桃花
眼角桃花 2020-12-10 20:17

I have a page with URL http://arslan/admin/category/index/0/name/asc/10 in Codeigniter. In this URL, the uri_segment start from 0. This (0

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 21:17

    I extend the session class by creating /application/libaries/MY_Session.php

    class MY_Session extends CI_Session {
    
        function __construct() {
            parent::__construct();
    
            $this->tracker();
        }
    
        function tracker() {
            $this->CI->load->helper('url');
    
            $tracker =& $this->userdata('_tracker');
    
            if( !IS_AJAX ) {
                $tracker[] = array(
                    'uri'   =>      $this->CI->uri->uri_string(),
                    'ruri'  =>      $this->CI->uri->ruri_string(),
                    'timestamp' =>  time()
                );
            }
    
            $this->set_userdata( '_tracker', $tracker );
        }
    
    
        function last_page( $offset = 0, $key = 'uri' ) {   
            if( !( $history = $this->userdata('_tracker') ) ) {
                return $this->config->item('base_url');
            }
    
            $history = array_reverse($history); 
    
            if( isset( $history[$offset][$key] ) ) {
                return $history[$offset][$key];
            } else {
                return $this->config->item('base_url');
            }
        }
    }
    

    And then to retrieve the URL of the last page visited you call

    $this->session->last_page();
    

    And you can increase the offset and type of information returned etc too

    $this->session->last_page(1); // page before last
    $this->session->last_page(2); // 3 pages ago
    

    The function doesn't add pages called using Ajax to the tracker but you can easily remove the if( !IS_AJAX ) bit to make it do so.

    Edit: If you run to the error Undefined constant IS_AJAX, assumed IS_AJAX add the line below to /application/config/constants.php

    define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
    

提交回复
热议问题