How to run Magento session into an external site?

In: Feeling guru|Techie Daw

13 Apr 2009

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:

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

// Initialize Magento
Mage::app("default");

// 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");

if($session->isLoggedIn())
{
    echo "Logged in";
}else{
    echo "Not logged in";
}

** Updated **
For users of Magento version 1.4.0.1, 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.

61 Responses to How to run Magento session into an external site?

Avatar

Benjie PHILIPPINES

April 14th, 2009 at 3:56 pm

galing!!!!

Avatar

Richard Feraro PHILIPPINES

April 14th, 2009 at 6:29 pm

thanks 🙂

Avatar

amartinez SPAIN

April 22nd, 2009 at 7:23 pm

Thanks a lot!

Uhmmm do you like this?

require_once ‘app/Mage.php’;
umask(0);
Mage::app(“default”)->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$profile = Mage::getModel(‘dataflow/profile’);
$userModel = Mage::getModel(‘admin/user’);
$userModel->setUserId(2); // or whatever else
Mage::getSingleton(‘admin/session’)->setUser($userModel);

Avatar

Richard Feraro PHILIPPINES

April 23rd, 2009 at 10:45 am

@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 🙂

Avatar

How to add a product into Magento from an external site? « My Silly Point of View UNITED STATES

April 27th, 2009 at 2:28 pm

[…] the Mage.php file on top of the process.php. Click here to see how. Then proceed with the php script […]

Avatar

Hassan BANGLADESH

July 29th, 2009 at 4:46 pm

Hi,

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

Thanks!

Avatar

Richard Feraro PHILIPPINES

July 29th, 2009 at 5:17 pm

The code snippets I have here on my blog are tested using Magento version 1.2.1.2.
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:

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

// Initialize Magento
Mage::app("default");

// 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");

if($session->isLoggedIn())
{
    echo "Logged in";
}else{
    echo "Not logged in";
}

Avatar

Greg UNITED STATES

August 7th, 2009 at 7:51 am

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

Avatar

Richard Feraro PHILIPPINES

August 7th, 2009 at 11:05 am

Hassan, can you post here your script so we can replicate it and see where it fails?

Avatar

Manegto – Using wordpress as a front door

January 14th, 2010 at 4:33 am

[…] Recently I have been trying? to use Magento as backend system while implementing its e-commerce functionality to a website created using wordpress .. what else .? I found this piece of code that will enable me to add Magento?s data into my wordpress site: from mysillysite […]

Avatar

John UNITED STATES

January 24th, 2010 at 5:09 am

Hey this isn’t working for me. When I include this in WordPress, I get a blank screen.

Avatar

Richard Feraro

January 24th, 2010 at 6:06 am

How do you add the php codes? Provide more details as to how you execute it.

Avatar

utto THAILAND

February 18th, 2010 at 8:21 pm

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?

Avatar

Richard Feraro UNITED STATES

February 18th, 2010 at 10:35 pm

Can you post your code here as to how you used the code so I can help you? It will also help if you tell us the version of your WordPress and Magento.

Avatar

utto THAILAND

February 18th, 2010 at 11:32 pm

magento 1.3.2.4 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.

Avatar

Richard Feraro

February 19th, 2010 at 3:51 am

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.

umask(0);

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

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

Avatar

utto THAILAND

February 19th, 2010 at 11:12 am

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

Avatar

Richard Feraro UNITED STATES

February 19th, 2010 at 4:18 pm

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 1.2.1.2. 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.

Avatar

Tim Jukes UNITED KINGDOM

March 23rd, 2010 at 9:39 am

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.

Thanks

Avatar

Richard Feraro

March 23rd, 2010 at 11:30 am

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.

<?php
error_reporting(E_ALL);

Avatar

Tim Jukes UNITED KINGDOM

March 23rd, 2010 at 5:06 pm

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!

Avatar

Tim Jukes UNITED KINGDOM

March 23rd, 2010 at 5:26 pm

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!

Avatar

Richard Feraro UNITED STATES

March 23rd, 2010 at 6:56 pm

@tim:
Check this one also http://www.magentocommerce.com/boards/viewthread/17316/
It seems there’s a function collision between magento and wordpress.

Avatar

Richard Feraro UNITED STATES

March 25th, 2010 at 10:33 pm

I have an update for this post. For users of Magento version 1.4.0.1, click here

Avatar

Richard Feraro UNITED STATES

April 8th, 2010 at 9:57 pm

Check my new post on how to use Magento’s session within WordPress:
http://mysillypointofview.wordpress.com/2010/04/08/how-to-use-magentos-session-within-wordpress/

Avatar

Richard Feraro UNITED STATES

April 8th, 2010 at 9:56 pm

Check my own approach in integrating Magento’s session within WordPress
http://mysillypointofview.wordpress.com/2010/04/08/how-to-use-magentos-session-within-wordpress/

Avatar

utto THAILAND

February 19th, 2010 at 7:22 pm

Thanks Richard ^ ^

Avatar

Richard Feraro PHILIPPINES

March 23rd, 2010 at 11:45 am

@utto:
how about installing the magento folder ‘outside’ the wordpress directory?

Avatar

Richard Feraro UNITED STATES

April 8th, 2010 at 9:54 pm

Avatar

Beok GERMANY

January 29th, 2010 at 9:32 pm

thanks!

Avatar

Richard Feraro UNITED STATES

February 18th, 2010 at 10:36 pm

Sure! You’re welcome Beok

Avatar

Roy Vincent PHILIPPINES

February 4th, 2010 at 4:21 pm

its not working…. its always says bool(false) when var_dump used… im using the latest magento… ver. 1.3.2.4

Avatar

Richard Feraro PHILIPPINES

February 6th, 2010 at 3:40 pm

it will help if you post your code here.

Avatar

Jon UNITED STATES

February 6th, 2010 at 7:53 am

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.

Avatar

Richard Feraro PHILIPPINES

February 6th, 2010 at 3:39 pm

you’re welcome 🙂

Avatar

pac PORTUGAL

March 15th, 2010 at 6:58 am

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?

thnaks

Avatar

Richard Feraro PHILIPPINES

March 23rd, 2010 at 11:36 am

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

<?php
// extracts the return_url
$this->get('return_url');
// sets the return_url
$this->set('return_url', htmlentities($_GET['return']));

Avatar

How to run Magento (version 1.4.0.1) session into an external site? « My Silly Point of View UNITED STATES

March 25th, 2010 at 10:20 pm

[…] Feraro — Leave a comment March 25, 2010 This post is an update for my blog entry on how to extend the Magento session to an external site but instead of using the version 1.2.1.2, I used the the latest stable version as of this writing […]

Avatar

vesvello UNITED STATES

April 6th, 2010 at 12:02 pm

I am trying to run magento code from external page with this:
require_once ?app/Mage.php?;
umask(0);
Mage::app();
but averytime I run the page I got this:
The webpage at http://www.midominio.com/ has resulted in too many redirects.
Any ideas?

Avatar

Richard Feraro UNITED STATES

April 6th, 2010 at 3:20 pm

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?

Richard

Avatar

Vesvello UNITED STATES

April 6th, 2010 at 10:33 pm

Well it was my mistake the line is:

Require_once (?/www/app/Mage.php?);

Avatar

Richard Feraro UNITED STATES

April 6th, 2010 at 10:59 pm

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?

Avatar

vesvello UNITED STATES

April 7th, 2010 at 6:16 am

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?

Avatar

Richard Feraro

April 7th, 2010 at 10:41 am

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.

Avatar

vesvello UNITED STATES

April 7th, 2010 at 1:34 pm

I try to integrate wordpress with magento trought this extension:

http://www.magentocommerce.com/wiki/development/integrate_wordpress_and_magneto

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

Avatar

Richard Feraro

April 8th, 2010 at 4:05 am

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.

Avatar

vesvello UNITED STATES

April 8th, 2010 at 5:35 am

I think your are right. Any ideas?

Avatar

Richard Feraro UNITED STATES

April 8th, 2010 at 9:55 pm

Avatar

Wu Di SINGAPORE

April 21st, 2010 at 2:15 pm

Thanks so much! this post is of great help!

Avatar

Richard Feraro UNITED STATES

April 21st, 2010 at 4:07 pm

You’re welcome Wu Di!

Avatar

Justin UNITED STATES

May 18th, 2010 at 4:30 am

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?

Avatar

Richard Feraro UNITED STATES

May 21st, 2010 at 4:24 pm

Hmm I think that would post security issues unless you’re gonna access it thru other means except http.

Avatar

sabnam

May 27th, 2010 at 9:59 pm

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….

“frontend”));
$session = Mage::getSingleton(“customer/session”);
if(!($session->isLoggedIn()))
{
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’));
exit;
}
else
{
header(“Status: 301”);
header(“Location: http://ABC.com “);
exit;
}
?>

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 ABC.com..how can that be achieved..i tried geturl() and seturl() but didn`t worked :(..

Avatar

Richard Feraro UNITED STATES

May 27th, 2010 at 10:32 pm

Try using:

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

or

Mage::_redirect(...);

or another sample

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

Check the samples here
This can also help you.

Avatar

sabnam

May 27th, 2010 at 10:54 pm

Thanks Richard for the help and this awesome blog.

I found that this solution also works …
if(!($session->isLoggedIn()))
{
Mage::getSingleton(‘customer/session’)->setBeforeAuthUrl($this->getRequest()->getRequestUri());

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…..

Avatar

Richard Feraro UNITED STATES

May 27th, 2010 at 11:13 pm

Glad that you figured it out 🙂 Keep on reading.

Avatar

How to add a product into Magento shopping cart from an external site? PHILIPPINES

June 4th, 2010 at 5:38 pm

[…] the Mage.php file on top of the process.php. Click here to see how. Then proceed with the php script […]

Avatar

How to run Magento (version 1.4.0.1) session into an external site? PHILIPPINES

July 9th, 2010 at 3:51 pm

[…] post is an update for my blog entry on how to extend the Magento session to an external site but instead of using the version 1.2.1.2, I used the the latest stable version as of this writing […]

Avatar

jancor UNITED STATES

August 19th, 2011 at 12:06 pm

Don’t forget about translation init : Mage::app()->getTranslator()->init(‘frontend’);

Avatar

Hiren Prajapati INDIA

September 10th, 2012 at 10:48 pm

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.

Hiren

Avatar

Richard Feraro PHILIPPINES

September 10th, 2012 at 11:46 pm

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 🙂

Comment Form

About my blog

This blog is targeted towards all levels of developers and also designers. Various topics are discussed such as Magento, PHP & MySQL, jQuery, WordPress, CSS and HTML.

Booking.com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 24 other subscribers

WordPress + Magento

Recent Trackbacks

Archives

Disclaimer

All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or my mom.