在Codeigniter中点击计数器

时间:2015-07-28 18:12:15

标签: php html codeigniter web hitcounter

我有以下代码:

(逐步)

  1. counter.txt放入APPPATH . 'logs/counter.txt'
  2. counter_helper.php;
  3. 中设置APPPATH . 'helpers/counter_helper.php'
  4. APPPATH . 'config/autoload.php'文件中自动加载新创建的帮助程序;
  5. MY_Controller.php
  6. 中设置APPPATH . 'core/MY_Controller.php'
  7. 任何控制器都应扩展MY_Controller而不是CI_Controller;
  8. 在页面上回复:<?php echo $this->count_visitor;?>
  9. 帮助者:

    <?php defined('BASEPATH') OR exit('No direct script access allowed.');
    
    if ( ! function_exists('count_visitor')) {
        function count_visitor()
        {
            $filecounter=(APPPATH . 'logs/counter.txt');
            $kunjungan=file($filecounter);
            $kunjungan[0]++;
            $file=fopen($filecounter, 'w');
            fputs($file, $kunjungan[0]);
            fclose($file);
            return $kunjungan[0];
        }
    }
    

    核心:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class MY_Controller extends CI_Controller
     {
      public $count_visitor;
      public function __construct()
       {
         parent::__construct();
          $this->count_visitor = count_visitor();
       }   
     }
    /* End of file MY_Controller.php */
    /* Location: ./application/core/MY_Controller.php */
    

    控制器:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
     class Home extends MY_Controller {
     public function index() {
     $data=array('isi'      =>'home/index_home');
    $this->load->view('layout/wrapper',$data); 
     }
    }
    

    观点:

    <?php echo $this->count_visitor;?>
    

    代码返回如下错误: enter image description here

2 个答案:

答案 0 :(得分:2)

I got it to work fine when I loaded the helper $this->load->helper('counter');

application > core > MY_Controller.php

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

class MY_Controller extends CI_Controller
{
    public $count_visitor;

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('counter');
        $this->count_visitor = count_visitor();
    }   
}

答案 1 :(得分:0)

是的,必须加载助手:

$this->load->helper('counter');

config / autoload.php: $autoload['helper'] = array('counter');