I'm using this code to login a customer programmatically:

require_once ("app/Mage.php");    


// Init a Magento session. This is super ultra important
Mage::getSingleton('core/session', array('name' => 'frontend'));

// $customer Mage_Customer_Model_Customer
// We get an instance of the customer model for the actual website
$customer = Mage::getModel('customer/customer')

// Load the client with the appropriate email
$email = "[email protected]";

// Get a customer session
$session = Mage::getSingleton('customer/session');

// Login an check the customer by his database userId
if ($session->loginById($customer->getId())) {
    echo '<div>Succesfull loginById</div>';
} else {
    echo '<div>Error in loginById</div>';

if ($session->isLoggedIn()) {
    echo '<div>Welcome</div>';
} else {
    echo '<div>Denied</div>';

But it's not working, the result I'm getting in the browser is:

Succesfull loginById


What could be the issue here?


Some new information: I've tried this script on a different shop we have running and it works perfectly there. Why would it work on one but not the other?


More troubleshooting has resulted in the conclusion that $session->getId() returns NULL while it should return an actual ID. Still no idea why this shop doesn't return a session id while the other one does.

  • Where you using this code?
    – vinothavn
    Oct 7, 2015 at 9:38
  • 1
    In a PHP script outside of Magento, I've included app/Mage.php in the script.
    – Rias
    Oct 7, 2015 at 9:43
  • Please update the full code
    – vinothavn
    Oct 7, 2015 at 9:46
  • Updated, added the require statement
    – Rias
    Oct 7, 2015 at 9:48
  • @Rias have checked your code and looks perfectly fine Oct 7, 2015 at 9:51

2 Answers 2


You're looking for


Where $customer is a loaded instance of Mage_Customer_Model_Customer

  • Adding this doesn't really seem to change anything.
    – Rias
    Oct 7, 2015 at 9:33
  • setCustomerAsLoggedIn() is already available in loginById() function Oct 7, 2015 at 9:49
  • Code works for me. loginById() loads the customer model again so you should go with setCustomerAsLoggedIn() anyway. Ensure your email has an active account. Oct 7, 2015 at 10:07
require_once ("app/Mage.php");

$websiteId = 1;
Mage::run('store_view_code', 'store');
Mage::init($websiteId, 'website');

$email = '[email protected]';

$customer = Mage::getModel('customer/customer');
$session = Mage::getSingleton('customer/session');

if ($customer->getId()) {

    $url = 'http://www.domain.com/test';
    header('Location: ' . $session->getAfterAuthUrl());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.