简体   繁体   中英

call a helper function in controller in codeigniter

I created a helper for visit hits and it contains a function which inserts some data in to the database:

hits_counter_helper.php :

function count_hits($options = array())
{

    //Determine whether the user agent browsing your site is a web browser, a mobile device, or a robot.
    if ($this->agent->is_browser())
    {
        $agent = $this->agent->browser() . ' ' . $this->agent->version() . ' - ' . $this->agent->platform();
    }
    elseif ($this->agent->is_robot())
    {
        $agent = $this->agent->robot();
    }
    elseif ($this->agent->is_mobile())
    {
        $agent = $this->agent->mobile();
    }
    else
    {
        $agent = 'Unidentified User Agent';
    }

    //Detect if the user is referred from another page
    if ($this->agent->is_referral())
    {
        $referrer = $this->agent->referrer();
    }

    // correcting date time difference by adding 563 to it.
    $date = date('Y-m-j H:i:s', strtotime(date('Y-m-j H:i:s')) + 563);

    $data = array (

        'page_Address'  =>   current_url(),

        'user_IP'       =>   $this->input->ip_address(),

        'user_Agent'    =>   $agent,

        'user_Referrer' =>   $referrer,

        'hit_Date'      =>   $date

    );

    $this->db->insert('counter', $data);

}

once I auto loaded the helper and called this function in my controller as:

My_controller.php :

public function index() {
    count_hits();
    //index code here
}

The problem is that I am getting a blank page and other codes does not run I think. What am I doing wrong?!

Add the following code to the beginning of your helper function:

//get main CodeIgniter object
$CI =& get_instance();

Replace all $this with $CI in your function.

and then load the helper function wherever you want in your controller like this:

count_hits();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM