Thursday, February 23, 2012

external php calling login into magento

Magento contains its own call to session_start() when included into your php application.
To ensure that your session set is the same session as magento front end, you will need to include magento in this manner:


require_once("pathtomagento/includes/config.php");
require_once("pathtomagento/shop/app/Mage.php");


umask(0);
Mage::app();
//this is the magic call to ensure the session of front end tally with your php session

Mage::getSingleton('core/session', array('name'=>'frontend'));

To set someone as logged in:
$oCustomer = Mage::getSingleton('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->load(#id);


$oSession = Mage::getSingleton('customer/session');
$oSession->setCustomerAsLoggedIn($oCustomer);


Updated 2012 feb 25:
This method seems to lack of event triggering when customer is logged in.
When you login as a member A, view a product X. Then logout and view product X. Then login as member A again and view product X,
It will cause the product to be directed to an error 404.
This is due to an error in report log which caused a duplicate in table: report_viewed_product_index. Duplicate entry for UNQ_NEOSHOP_REPORT_VIEWED_PRODUCT_INDEX_CUSTOMER_ID_PRODUCT_ID (to be exact) Observer class triggered: app/code/core/Mage/Reports/Model/Event/Observer.php, method: catalogProductView

Suppose, when some logged in, it will trigger several core events, which related to "customer_login", but this does not seems to work when there is not front controller been dispatched.
One way to fix it is to run a action on the front controller and then continue with the code.
But problem is, the default module "" will trigger module cms which will display entire html of the magento cms front page.
To fix this, add your own custom controller, and a dummy action which does not echo anything.
And call magento to run this front controller by calling this way:

umask(0);
//this will enable sensitive error
//Mage::setIsDeveloperMode(true);
$oMageApp = Mage::app();
$oMageApp->getRequest()->setModuleName("yourmodulename");
$oMageApp->getRequest()->setActionName('yourmoduledummymethodname');
$oMageApp->getFrontController()->dispatch();

No comments: