Magento 1.9 – How to Set Cookie on Login

cookiemagento-1.9

So I've installed a new chat for my website but need to do one last thing, and that is to set a cookie on login, and delete it on log out.

Code I'll be using for login:

setcookie('cc_data',$userid, time() + (86400 * 30), "/");

Code I'll use to unset the cookie:

setcookie('cc_data', '', -time() + (86400 * 30), "/");

The part I need help with is where exactly to place this. Obviously I need the customer ID for $userid so it needs to be after the login.

Disregarding all the "should not edit core files", is AccountController the correct file for this? I can add it in a more correct way in the future, but currently I'm just looking for my target file/function.

Best Answer

Create a simple Module in local namespace and add 2 directories and 2 files

/app/code/local/Your/Module/etc/config.xml
/app/code/local/Your/Module/Model/Observer.php

config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Your_Module>
            <version>1.0.0</version>
        </Your_Module>
    </modules>
    <global>
        <models>
            <Your_Module>
                <class>Your_Module_Model</class>
            </Your_Module>
        </models>
        <events>
        <customer_login>
            <observers>
                <Your_Module>
                    <type>model</type>
                    <class>Your_Module/observer</class>
                    <method>customerLogin</method>
                </Your_Module>
            </observers>
        </customer_login>
        <customer_logout>
            <observers>
                <Your_Module>
                    <type>model</type>
                    <class>Your_Module/observer</class>
                    <method>customerLogout</method>
                </Your_Module>
            </observers>
        </customer_logout>
        </events>
    </global>
</config>

Observer.php

class Your_Module_Model_Observer
{

    public function customerLogin($observer)
    {
        $value = $userid // from whatever
        Mage::getModel(‘core/cookie’)->set('cc_data', $value);
    }

    public function customerLogout($observer)
    {
        Mage::getModel(‘core/cookie’)->delete('cc_data');
    }
}

you will also need a module xml file to enable your module, copy an adjust one from

/app/etc/modules/