I autoload the Session library in CodeIgniter. However, sometimes there are controllers that output XML, JSON, an image, or other mime types, and I don't want these sending back cookies in the header. Is there a way to suppress this on a per-controller basis?

Recommended Answers

All 5 Replies

Thanks for the link!

... But I'm still not marking this thread as solved because that link just basically said I was shit outta luck.

If you are using a MY_Controller with CI already, add a property called $ignore_cookies defaulting it to FALSE. In your controller setting the $ignore_cookies variable to TRUE will prevent the cookies from being set.

Extend /system/core/Security.php CI_Security with a MY_Security and override the csrf_set_cookie() method.

<?php

class MY_Security {

    public function __construct()
    {
        parent::__construct();
    }

    public function csrf_set_cookie()
    {

        $CI =& get_instance();

        if( !isset( $CI->ignore_cookies ) || (bool) $CI->ignore_cookies === FALSE ){
            return parent::csrf_set_cookie();
        }

        log_message('debug', "CRSF cookie set skipped");

        return $this;
    }
}

Extend /system/libraries/Session.php CI_Session with a MY_Session and override the _set_cookie() method

<?php

class MY_Session extends CI_Session
{
    public function __construct()
    {
        parent::__construct();
    }

    public function _set_cookie( $cookie_data = NULL )
    {
        $CI =& get_instance();

        if( !isset( $CI->ignore_cookie ) || (bool) $CI->ignore_cookie === FALSE ){
            parent::_set_cookie( $cookie_data );
        }
    }
}

When CI serves a request it will proxy through the MY_* instances and then pass the requests on as necessary to the core functions. This should prevent any cookies from being set.

I did some stepping through the code and at a cursory glance this seems to the be two points where cookie headers get set on a normal request. Note: I did not give these a thorough testing and I believe the modifications to the security class will disable csrf protection for those particular requests.

Member Avatar for diafol

WRT disabling csrf, I came across this a while back and decided it wasn't worth the hassle for the overhead improvement. There again, my concurrents were barely in single figures! .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.