Skip to main content

Magento: Check if Customer Logged in

Magento offers a simple way to include the application from an external script but getting the customer session data into your external page can be a real pain. This simple tutorial gives you the information you need to use Magento customer session data in an external script hosted outside of the core Magento folder.

I am currently working on some bespoke web applications and services using Magento as firewall to assess if a user is both logged in and if the user has paid for a particular item.

This means that I can offer paid for access to web applications and VIP areas of websites.

Take a look at the following script:

//LOAD MAGENTO
require_once 'YOUR_PATH_TO_MAGENTO/app/Mage.php';
umask(0);
Mage::app('YOUR_WEBSITE_CODE', 'website');
//GET SESSION DATA
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));
$customer_data = Mage::getModel('customer/customer')->$session->id);
//CHECK IF LOGGED IN
if($session->isLoggedIn()){
echo 'Welcome ' . $customer_data->firstname . " " . $customer_data->lastname;
} else {
echo "Access Denied: Sorry, but this page is for registered members only.";
exit;
}

The code is very simple but there are 2 very important things to be aware of.

  1. Mage::app('YOUR_WEBSITE_CODE', 'website') - Make sure you have defined a scope for Magento to use.
  2. Mage::getSingleton('core/session', array('name'=>'frontend')) - Make sure you have called the core session data first before attempting to use the customer session.

Following these steps you should now have the ability of providing restricted access to your web applications and VIP pages.

Looking for Expert WordPress or Drupal development?

I am a freelance website developer and designer based in the UK. I work as a remote Drupal developer, WordPress developer and Front-end developer for a variety of startups, charities and international businesses in Bristol, Bath, London and Europe. You can learn more about me by visiting my resume page.

Get in touch for a free quote on your next project and if you want to connect me with then check out my LinkedIn profile.