0

I would like to return a csrf inside my helper function in Codeigniter.

but $this key is not working according to this post,

I try to use $CI =& get_instance(); , but gives me Undefined variable: CI

please see below codes


    if ( !function_exists('refresh_token')){

    $CI =& get_instance(); 
        function refresh_token(){
            return $CI->security->get_csrf_hash() ; 
        }
    }

controller :

public function delete_data(){

     $token = refresh_token(); 
              $array = array(
                      $this->security->get_csrf_token_name() => $token,
                      'data'=> "hi",
              );
              echo json_encode($array);  


}

Errors :

A PHP Error was encountered
Severity: Notice

Message: Undefined variable: CI

I see lots post, they all recommend using get_instance(), but teach me if makes something wrong thanks in advance.

Max Voitko
  • 1,542
  • 1
  • 17
  • 32
Leong
  • 139
  • 13

1 Answers1

0

Functions have their own scope in PHP, you have to pass CI into your function or declare it within your function

e.g.

if ( !function_exists('refresh_token'))
{
    function refresh_token()
    {
        $CI = get_instance();
        return $CI->security->get_csrf_hash() ; 
    }
}

Take a look at https://www.php.net/manual/en/language.variables.scope.php for more informations

Atural
  • 5,389
  • 5
  • 18
  • 35