绑定到CodeIgniter钩子的辅助函数返回HTTP 500错误求助
Problem Context
I built a helper file at application/helpers/test.php with this code:
if ( ! function_exists('testdemo')) { // 检查函数是否存在,不存在则创建函数 testdemo($id=false){ $CI =& get_instance(); // 获取CI实例 echo $CI->session->userdata('user_info'); exit; } }
Then I attempted to bind it to the pre_controller hook in application/config/hooks.php:
$hook['pre_controller'] = array( 'class' => '', 'function' => 'testdemo', 'filename' => 'test.php', 'fi...
But this setup throws an HTTP 500 error. I need help figuring out why this is happening.
Root Causes & Fixes
Let’s walk through the issues step by step:
1. Critical Syntax Error in the Helper Function
Your testdemo function definition is missing the function keyword—this is a basic syntax mistake that will immediately trigger a 500 error.
Fixed helper code (application/helpers/test.php):
if ( ! function_exists('testdemo')) { function testdemo($id=false){ // Added required "function" keyword $CI =& get_instance(); // Session issue addressed next echo $CI->session->userdata('user_info'); exit; } }
2. Session Library Isn’t Available in pre_controller Hook Stage
CodeIgniter’s pre_controller hook runs before any controller is loaded, and by default, the Session library isn’t initialized at this point. Calling $CI->session directly will throw an "Undefined property" error, leading to a 500.
Fix Options:
- Option 1: Manually load the Session library inside your helper
if ( ! function_exists('testdemo')) { function testdemo($id=false){ $CI =& get_instance(); $CI->load->library('session'); // Manually initialize session library echo $CI->session->userdata('user_info'); exit; } } - Option 2: Use a later hook stage
Switch topost_controller_constructorinstead ofpre_controller—this runs after the controller is initialized, so if your controller (or global config) loads the Session library, it will be available here.
3. Incomplete Hook Configuration
Your hook config is cut off at 'fi...'—you need to add the filepath parameter pointing to the helpers directory (since your helper lives in application/helpers).
Complete hook config (application/config/hooks.php):
$hook['pre_controller'] = array( 'class' => '', 'function' => 'testdemo', 'filename' => 'test.php', 'filepath' => 'helpers', // Add this missing line 'params' => array() // Optional: include parameters if needed );
Quick Additional Checks
- Confirm hooks are enabled in
application/config/config.php:$config['enable_hooks'] = TRUE; - Ensure
test.phphas proper file permissions (typically 644) so your web server can read it.
内容的提问来源于stack exchange,提问作者Juliver Galleto

