onlinecode

Magento – login customer programmatically Magento 1.9

Magento – How to login customer programmatically

This post show login customer programmatically in Magento. In this given code will allow to login user/customer to login if they are not logion already. If user is not login then this code create session and allow and set seesion and allow login in magento website to user programmatically.

function user_login( $user_email , $user_password ) {
    umask(0);
    ob_start();
    session_start();
    Mage::app('default');
    Mage::getSingleton("core/session", array("name" => "frontend")); // get Singleton of session 
    $website_Id   = Mage::app()->getWebsite()->getId(); // get id of store or website
    $store_detail = Mage::app()->getStore(); 
    $uses_detail = Mage::getModel("customer/customer");
    $uses_detail->website_id = $website_Id;
    $uses_detail->setStore( $store_detail );
    try
    {
        $uses_detail->loadByEmail( $user_email );
        $session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($uses_detail);
        $session->login( $user_email , $user_password );
    }
    catch(Exception $exception)
    {
        echo $exception->getMessage(); // print Exception Message
    }
}

// check user is login or not
if(!Mage::getSingleton('customer/session')->isLoggedIn()) 
{
    $user_email = "example@mail.com"; // user email id
    $user_password = "add magento login password";
    user_login( $user_email , $user_password );    
}
else
{
    echo "user is already login";
}
Exit mobile version