Codeigniter - 挂钩记录GET / POST请求

时间:2013-01-07 11:47:32

标签: codeigniter post logging get hook

客户要求记录所有GET / POST请求并将其存储90天以用于其应用程序。我写了一个HOOK,似乎记录了一些GETS / POSTS,但数据少于我的预期。例如,在提交表单数据时,条目似乎不会放入日志中。有人写过类似的东西吗?

到目前为止,这是我的版本:

class Logging {

    function __construct() {
        $this->CI =& get_instance();
    }

    function index() {
        $this->CI->load->model('Logging_m');
        $this->CI->load->model('Portal_m');

        //get POST and GET values for LOGGING        
        $post = trim(print_r($this->CI->input->post(), TRUE));
        $get = trim(print_r($this->CI->input->get(), TRUE));

        $this->CI->Logging_m->logPageView(array(
                'portal_id' => $this->CI->Portal_m->getPortalId(),
                'user_id' => (!$this->CI->User_m->getUserId() ? NULL : $this->CI->User_m->getUserId()),
                'domain' => $_SERVER["SERVER_NAME"],
                'page' => $_SERVER["REQUEST_URI"],
                'post' => $post,
                'get' => $get,
                'ip' => $this->CI->input->ip_address(),
                'datetime' => date('Y-m-d H:i:s')
        ));
    }

}

此数据存储在名为“Logging_m”的模型中。看起来像这样:

<?php 
class Logging_m extends CI_Model {

  function __construct() {
    parent::__construct();
  }

  function logPageView($data) {
    $this->db->insert('port_logging', $data);
  }

}

/* End of file logging_m.php */
/* Location: ./application/models/logging_m.php */

1 个答案:

答案 0 :(得分:12)

正如Patrick Savalle所提到的,你应该使用钩子。使用post_controller_constructor挂钩,以便您可以使用所有其他CI内容。

1)在./application/config/config.php设置$config['enable_hooks'] = TRUE

2)在./application/config/hooks.php中添加以下钩子

$hook['post_controller_constructor'] = array(
    'class' => 'Http_request_logger',
    'function' => 'log_all',
    'filename' => 'http_request_logger.php',
    'filepath' => 'hooks',
    'params' => array()
);

3)创建文件./application/hooks/http_request_logger.php并添加以下代码作为示例。

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Http_request_logger {

    public function log_all() {
        $CI = & get_instance();
        log_message('info', 'GET --> ' . var_export($CI->input->get(null), true));
        log_message('info', 'POST --> ' . var_export($CI->input->post(null), true));                
        log_message('info', '$_SERVER -->' . var_export($_SERVER, true));
    }

}

我已经对它进行了测试,它适用于我(确保在配置文件中激活了日志记录)。

相关问题