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:

require_once 'YOUR_PATH_TO_MAGENTO/app/Mage.php';
Mage::app('YOUR_WEBSITE_CODE', 'website');

Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));
$customer_data = Mage::getModel('customer/customer')->$session->id);

echo 'Welcome ' . $customer_data->firstname . " " . $customer_data->lastname;
} else {
echo "Access Denied: Sorry, but this page is for registered members only.";

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.