Recently I received a programming task requiring to use Magento as backend system while implementing its e-commerce functionality to a website created using CodeIgniter framework. After reading a book related to the software mentioned, I found this piece of code that will enable me to use all Magento’s power into my custom website:

// Include Magento application
require_once ( "/var/www/your-magento-directory/app/Mage.php" );

// Initialize Magento

// You have two options here,
// "frontend" for frontend session or "adminhtml" for admin session
Mage::getSingleton("core/session", array("name" => "frontend"));

That’s it! You can now use the internal classes and functions of Magento into your site. For example, the code below validates whether a customer is logged in or not by checking the Magento session:

$session = Mage::getSingleton("customer/session");

    echo "Logged in";
    echo "Not logged in";

** Updated **
For users of Magento version, click here

About the author

Richard Feraro is a Magento Enterprise Certified developer from Manila, Philippines with 14 years of solid open-source development experience using Linux, Apache, MySQL & PHP.

By Richard Feraro

Richard Feraro is a Magento Enterprise Certified developer from Manila, Philippines with 14 years of solid open-source development experience using Linux, Apache, MySQL & PHP.

61 thoughts on “How to run Magento session into an external site?”
  1. Thanks a lot!

    Uhmmm do you like this?

    require_once ‘app/Mage.php’;
    $profile = Mage::getModel(‘dataflow/profile’);
    $userModel = Mage::getModel(‘admin/user’);
    $userModel->setUserId(2); // or whatever else

  2. @amartinez:
    Are you trying to initialize the admin session instead of the frontend session? If yes, you should add this right after Mage::app(“default”);

    Mage::getSingleton("core/session", array("name" => "adminhtml"));

    You could elaborate more what’s the purpose of your script so I can help you 🙂

  3. Hi,

    I check the isLoggedIn() status in Magento ver. 1.3.2. It always return “Not logged in”. Have you any other solution please?


    1. The code snippets I have here on my blog are tested using Magento version
      You can check the changelogs of the version 1.3.2 if there’s some bugs regarding the isLoggedIn() function. Have you tested the script I mentioned above? Try testing this script:

      // Include Magento application
      require_once ( "/var/www/your-magento-directory/app/Mage.php" );
      // Initialize Magento
      // You have two options here,
      // "frontend" for frontend session or "adminhtml" for admin session
      Mage::getSingleton("core/session", array("name" => "frontend"));
      $session = Mage::getSingleton("customer/session");
          echo "Logged in";
          echo "Not logged in";
      1. I think Richard’s code is probably right, but I’m thinking there can be some problems depending on cookie location. I’ve read that in Magento’s CMS you can put ‘/’ for cookie location, which will make the cookie available everywhere? Not sure about the logic of that, plus it doesn’t work for me. O__o

      1. I get a blank screen too. I add the code to my wp theme(comments.php). I trying to use magento session login for comment to wordpress. any idea?

      2. magento and wordpress 2.9.2 (install in directory “blog”)
        I just add
        require_once ( “../app/Mage.php” );
        page render blank

        if I create new page under “Blog” and put your code It’s work but not in theme.

        1. Try doing some check in your require_once line:

          require_once ( “/var/www/your-magento-directory/app/Mage.php” ); // this should be an absolute URL to yout Mage.php file. You are using a relative URL based on your example.


          // this line should throw an error if Mage.php fails to load
          Mage::getSingleton(“core/session”, array(“name” => “frontend”));

          $session = Mage::getSingleton(“customer/session”);

        2. I have tried absolute URL and put all code, page display bank again. if wrong path ,page display error.

          Maybe session conflict between mage and wp?

          I just want to pull customer name and email fill in name and email wp comment. T_T

        3. Hmm I think the new version of Magento introduced something that breaks the usual access to it. The script I used is tested on Magento version I’ll try to download a copy of it this weekend and test it to see what’s going on as well. I’ve been receiving alot of inquiry regarding the new version of Magento resulting to blank pages and cookies expiring preventing them to add products via URL too. I’ll update this thread about the result of my test.

        4. Hi Richard

          Did you ever find out any more about this? I’ve been able to get everything working fine on a simple php doc, but keep getting the blank page when trying to include it in WordPress.

          I’m including the file like this:

          require_once($_SERVER['DOCUMENT_ROOT']."/magento/app/Mage.php"  );

          in my theme’s header.php – using WordPress 2.9 and Magento 1.4.


        5. Hello Tim!

          Have you tried displaying the code below if does gives you the right absolute url?

          require_once($_SERVER['DOCUMENT_ROOT']."/magento/app/Mage.php" );

          also for those here who uses the script for wordpress, is your server configured to display errors? Try setting the error reporting to all.

        6. Hi Richard

          Thanks for replying so quickly! The error_reporting’s really helped – looks like a problem with

          Cannot redeclare __()

          in wp-includes/l10n.php:101 which has given me a great lead – will post back if I find a solution.

          Thanks again!

        7. Found a not ideal solution (I hate hacking the core), but if you find

          function __()
                   return Mage::app()->getTranslator()->translate(func_get_args());

          in magento/app/code/core/Mage/Core/functions.php

          and wrap it with a

           if (!function_exists('__')) { 

          conditional, that seems to do the trick. This particular function seems to be deprecated from version 1.3.

          Also worth wrapping the same conditional around

          function esc_attr__( $text, $domain = 'default' ) {
          		return esc_attr( translate( $text, $domain ) );

          in wp-includes/l10n.php on line 117

          Hope that’s helpful to someone!

  4. A huge thanks for this. I was trying to do everything except the “Mage::getSingleton(“core/session”, array(“name” => “frontend”));”, Magento was acting as if everything was working, but the cart (in my test) wasn’t actually being updated. Thanks again.

  5. perfect. it works very well.
    very usefull.
    Now do you know i it’s possible to if not logged in go to the magento log-in/register page and come back to the same page after logged-in?


    1. @pac:
      it can be done by getting/setting the return_url value.

      // extracts the return_url
      // sets the return_url
      $this->set('return_url', htmlentities($_GET['return']));
  6. I am trying to run magento code from external page with this:
    require_once ?app/Mage.php?;
    but averytime I run the page I got this:
    The webpage at has resulted in too many redirects.
    Any ideas?

    1. Hello vesvello,

      I’m just wondering, if you’re running Mage.php from an external page, why is it you’re require_once url is set to ‘app/Mage.php’? That will make your page run within magento installation folder right?


      1. I see 🙂

        I checked online and it seems it isn’t Magento that is causing that ‘too many redirect’ error. Possible causes are .htaccess settings, cookies, cache and or programming error. Try clearing the cache both your browser and Magento var/cache folder and include also the var/session folder then try it again.

        How do you use the code I posted in this article?

      2. I am trying t put together magento & wordpress and the problem is with .htaccess I need to add this that is creating the problem.

        RewriteRule .* ../index.php [L] (this call index.pho in magento)

        I dont know how to work with .htaccess but I think if I can make any rule to make an exception when i add require_one(“../app/mage.php’) in index.php from wordpress, maybe it can work

        Any advise?

      3. Can you explain how should that htaccess rewrite rule work? May I know also what are you trying to achieve in your code so I could suggest other ways to achieve without changing any of the server settings? It really seems that your rewrite rule is set to loop forever.

      4. I try to integrate wordpress with magento trought this extension:

        but i have my store in Spanish and English and I want the blog in both languages too.
        I know with Mage::app()->getLocale()->getDefaultLocale();
        I can get the language of the store but to run this inside wordpress I need to use the trick you post here into wordpress’ index.php
        Here is where I got the loop forever

        Another option was to change languages.phtml to create cookie to get the value:

        $idioma = Mage::app()->getLocale()->getDefaultLocale();
        setcookie(“idioma”,$idioma, time()+3600,”/”);

        but because of the changes in .htaccess (you can see this changes if you go to the extension above) wordpress can’t find the cookie.
        I found somewhere this code for .htaccess to manipulate the cookie but I dont understand a word.

        RewriteEngine On
        RewriteBase /
        RewriteCond %{HTTP_COOKIE} lang=([^;]+) [NC]
        RewriteRule ^(.*)$ /$1?cookie-value=%1 [R,QSA,L]

        thanks for your time

      5. Are you trying to run WordPress within Magento?s intallation or do you want to extend Magento?s session within WordPress? I saw that exact code which is also having the very same problem from someone?s blog article. Your problem isn?t actually Magento or WordPress related but rather server setting thru htaccess.

  7. Thanks for the posts on this topic!

    Are you aware of a way to access the mage.php file in the same way, but from an application on a separate server – without changing permissions on that file?

    We want to carry the high level cart information like price and item quantity between the website and the Magento store hosted on another server, so maybe you see a better way to do that?

  8. First of all thanks for this post…it really helped me a lot..

    I am having one small problem here…

    I have a magento CMS page which links to the module phtml which decides whether to let the user access external website or not….

    $session = Mage::getSingleton(“customer/session”);
    header(“Location:/customer/account/login/login_url/ “);
    Mage::getSingleton(‘core/session’)->addError($this->__(‘Before you can access ABC website you must first create an account or login with us’));
    header(“Status: 301”);
    header(“Location: “);

    here when the user is not logged in and is taken to dual page where he can either do the registration or login…after that he should be taken to can that be achieved..i tried geturl() and seturl() but didn`t worked :(..

    1. Try using:

      Mage::app()->getResponse()->setRedirect(...) ;



      or another sample

      header( 'Location: ' . Mage::helper('checkout/url')->getCheckoutUrl() );

      Check the samples here
      This can also help you.

  9. Thanks Richard for the help and this awesome blog.

    I found that this solution also works …

    it saves the url for where it will be redirected to after login/registration page…

    will be glad..if it will work for others too…..

  10. Hi Richard,

    Thank you very much for this helpful post!

    I have similar problem. First of all i would like to overview the exact problem.

    I have my external site setup in core php. I am using magento as a part of this parent site and i have to run the magento within iframe of parent website.

    Now what exactly I want is, if I logged in to the parent website than it should also logged me in to the magento front end site as a customer once I click on the magento link.

    I have managed the registration process. So if i register to the parent website than the record is also added to the magento database as a customer.

    I do not have any idea that how I synchronize the session of my external site into magento site.

    Our external site creates a sessionhash once user logged in to the site and it keeps the sessionhash throughout the whole user session and it uses this session hash to authenticate user on every page.

    Your quick help/solution would be really appreciated as I am running short of time.

    Thanks in advance.


    1. Hello Hiren,

      Make sure that your Magento application and the parent site share the same cookie and/or you should be able to generate the Magento cookie with the same cookie domain path with your parent site to share the same session.

      Thanks for dropping by 🙂

Leave a Reply