Reputation: 63
I am working on Codeigniter site and trying to implement User tracking functionality for visitors only (not registered users).
I want to track ( ip address, from_page, to_page, time_stamp) on every page redirect and as I want to track only temporary users I would need to access database too, to check whether account exists or not.
My question is where to write my code, so that Codeigniter automatically checks before each redirect, (keep in mind, that place should have rights to access database or sessions).
Checking in each controller file will make so much redundant code and I don't think htaccess file could do it .
-Thanks
Upvotes: 3
Views: 5524
Reputation: 12836
There are multiple ways to do this:
One is to create a helper file, say trackuser_helper.php
in the helpers folder. Create a function to do the tracking in this file (say trackUser()
). Then autoload this file inside config/autoload.php
like so:
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('trackuser'); //ignore the '_helper.php' portion of the filename
Now you can just call trackUser()
in every controller.
The second option which in my opinion is better is to use Hooks
provided by CodeIgniter
These are defined inside config/hooks.php
like so:
$hook['pre_controller'][] = array(
'class' => 'MyClass',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'hooks',
'params' => array('param1', 'param2', 'etc')
);
The array index correlates to the name of the particular hook point you want to use. In the above example the hook point is pre_controller. A list of hook points is found below. The following items should be defined in your associative hook array:
1.Class - The name of the class you wish to invoke. If you prefer to use a procedural function instead of a class, leave this item blank.
2.Function - The function name you wish to call. filename The file name containing your class/function.
3.Filepath - The name of the directory containing your script. Note: Your script must be located in a directory INSIDE your application folder, so the file path is relative to that folder. For example, if your script is located in application/hooks, you will simply use hooks as your filepath. If your script is located in application/hooks/utilities you will use hooks/utilities as your filepath. No trailing slash.
4.Params - Any parameters you wish to pass to your script. This item is optional.
This specifies which function call you want to execute before each controller load. This way you do not even need to add trackuser()
to each controller
. These hooks can be pre_controller
or post_controller
. You can read more about hooks at the CI documentation.
Upvotes: 1