Magento Login Customer Programmatically


Magento Login Customer Programmatically : In Magento sometimes we need to login customer programmatically. Here in this tutorial we have created a function in which we are passing email and password to login. We are going to explain how to login front end user programmatically.


Magento Login Customer Programmatically

Here is an example to login customer programmatically –

Magento Login Customer Programmatically:

<?php
function loginCustomer( $email, $password )
if (!empty($email) && !empty($password )) {
    require_once ("app/Mage.php");
    umask(0);
    $session = Mage::getSingleton('customer/session');
    $session->start();
    Mage::app('default');
    Mage::getSingleton("core/session", array("name" => "frontend"));

    $websiteid = Mage::app()->getWebsite()->getId();
    $store = Mage::app()->getStore();
    $customer = Mage::getModel("customer/customer");
    $customer->website_id = $websiteid;
    $customer->setStore($store);
    try {
        $customer->loadByEmail($email);
        $session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
        $session->login($email, $password);
		if ($session->getCustomer()->getIsJustConfirmed()) {
                            echo "Welcome! Logged In As ".$email;
                        }
    }catch(Exception $e){
      Mage::log("Error In Login".$e->getMessage());
    }
	}else{
	   $session->addError('Please Enter Username & Password.');
	}


  } 
?>

The above method accepts email & password to login in the system. You can add more validations and messages as per your requirement.

Note : The above example works for front end users/customers.

Advertisements

Add Comment

📖 Read More