Run Magento Code Outside of Magento

Posted on 03. Nov, 2008 by Fido in Development, Magento

Hi All -
Finally time for a new post! (Something I’m surprised I haven’t covered yet).
This post will inform you on how to run Magento code outside of Magento. All you need is to have access to Magento’s ‘app/Mage.php‘ file.

This will be handy code for a few things:

  • Integration with 3rd party items – shared sessions, or just shared themes
  • Ajax calls – although not the preferred solutions for Ajax calls, it is a quick and easy one


To expand on these ideas a bit more:
Integration:
-You can use this code to output HTML that is outputted in Magento anywhere. You might want to integrate Wordpress and steal the navigation from Magento, for instance. You might want to share sessions and users between your CMS and Magento (and even share the databases). This can help you get started on doing that.

Ajax:
-Because you can use this code to output any block/template, you can use it for Ajax calls in your Magento build. You build your block and template (and any other needed objects) as usual and output them via this code.

Here is a sample:

<?php
require_once 'app/Mage.php';
umask(0);
/* not Mage::run(); */
Mage::app('default');

// get layout object
$layout = Mage::getSingleton('core/layout');

//get block object
$block = $layout->createBlock('catalog/product_ajax');

/* choose whatever category ID you want */
$block->setCategoryId(3);
$block->setTemplate('catalog/product/ajaxevents.phtml');

echo $block->renderView();

?>

We can see in this block of code that we are grabbing the custom block ‘catalog/product_ajax‘.
This is simply a block that grabs a product collection. In this case, we are able to set the category id to 3. (See the post on custom blocks to help you get a feel for what this might look like).

This block is then setting the .phtml template to ‘ajaxevents.phtml‘ and rendering the view. You hopefully can see how this would be useful for Ajax calls.

Other code that might help you along your way:
From php architect’s book (might be outdated!!! We haven’t tested this particular code):

include('app/Mage.php');
Mage::App('base'); //might be "default"

$customer = Mage::getModel('customer/customer');
$customer->loadByEmail('some@email.address'); /* need a users email address */
$session = Mage::getSingleton('customer/session');
$session->start();

Here is some session code that will grab cart information. Notice that this code doesn’t start a session:

<?php

$mageFilename = 'app/Mage.php';
require_once $mageFilename;

umask(0);
Mage::app();

/* Magento uses different sessions for 'frontend' and 'adminhtml' */
Mage::getSingleton('core/session', array('name'=>'frontend'));

// $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// $cart = Mage::helper('checkout/cart')->getItemsCount();

$cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();

echo 'cart items count: ' . $cart;

?>

Yet another block of code with some interested stuff:

require_once 'app/Mage.php';
umask(0);

$app = Mage::app('default');

/* Init User Session */
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));

if ($session->isLoggedIn()) {
/* do something if logged in */
} else {
/* do something else if not logged in */
}

Tags: , , , , , ,

53 Comments

Fido

03. Nov, 2008

Sorry for the comments in the code – The theme being used might have some conflicting CSS with the Code viewer which is resulting in comments being floated to the right and having a background image :P

You’ll need to scroll to see them.

Unirgy

03. Nov, 2008

A more standard way to get block html:

// get layout object
$layout = Mage::getSingleton(’core/layout’);

// create block object
$block = $layout->createBlock(’catalog/product_ajax’);

/* choose whatever category ID you want */
$block->setCategoryId(3);
$block->setTemplate(’catalog/product/ajaxevents.phtml’);

// output block html
echo $block->toHtml();

Fido

03. Nov, 2008

Thanks unirgy. I’ve incorporated that into my code snippet.

James

04. Nov, 2008

I tried to use the session integration examples with the latest Magento, so far no success. :-(

Still, I have a project that really needs to integrate with the user sessions of a shopping cart and Magento is the most powerful option around.

My testing code:
———————————————————-
loadByEmail(’some@email.address’); /* need a users email address */
//$session = Mage::getSingleton(’customer/session’);
//$session->start();
$session = Mage::getSingleton(’customer/session’, array(’name’=>’frontend’));

echo(”");
print_r($session);
Reflection::export(new ReflectionClass(’Mage_Customer_Model_Session’));
echo(”");

echo($session->getCustomerId());

if ($session->isLoggedIn()) {
/* do something if logged in */
echo(”do something if logged in”);
} else {
/* do something else if not logged in */
echo(”do something else if not logged in”);
}
?>
———————————————————-

Fido

05. Nov, 2008

Check out these files:
app\code\core\Mage\Customer\Model\session.php
and
app\code\core\Mage\Customer\Model\customer.php

$customer = Mage::getModel(’customer/customer’)->loadByEmail(’email@address.com’);

$session = Mage::getModel(’customer/session’)->setCustomer($customer);
//can also try
//->login
//->setCustomerAsLoggedIn

Check out the files (and the ones they extend!) to check out starting a session and all that!

Fido

05. Nov, 2008

\app\code\core\Mage\Core\Model\Session\Abstract\Varien.php
This one contains the “start” function

\app\code\core\Mage\Core\Model\Session\session.php
This seems to mostly deal with session messaging

James

05. Nov, 2008

Found it.

Th secret to reinitializing the logged-in user’s session is to first instantiate ‘core/session’ and THEN ‘customer/session’.

So the magic lines to make the lest example work is:
. . .

Mage::getSingleton(’core/session’, array(’name’=>’frontend’));

$session = Mage::getSingleton(’customer/session’, array(’name’=>’frontend’));

. . .

pejie

16. Nov, 2008

do you have the sample code for ajaxevents.phtml?

Fido

17. Nov, 2008

Pejie, just check out “list.phtml” found here:

app\code\core\Mage\Catalog\Block\Product\list.phtml

This is the file I start with to do any product list output from my modules (it’s equipped to handle any product collection)

pejie

18. Nov, 2008

Thanks Fido, i thought the ajaxevents.phtml is another separate file….

Your magento code works outside magento but when I tried to run magento code in my CMS i got the “Fatal error: Cannot redeclare __autoload() in W:\www\magento\app\code\core\Mage\Core\functions.php on line 62″ because there is __autoload function declared in my CMS….. how can i solve this error?

Sirvash

19. Nov, 2008

Hi,

Above all example generates the records corresponding the category_id and customer depends on session very cool but if we wanna to find out all admin user details and all product list in single page.

anybody assist me.

Thanks
Sirvash Sharma

James

16. Dec, 2008

Anyone know how to load an object where I can fetch the price, discount and other Product related data?

Magento Hosting

14. Jan, 2009

Never tried this but I can see how useful it will be – will let you know my progress!

parky

15. Jan, 2009

pejie did you ever get an answer to your fatal error cannot redeclare autoload? I am getting the same with trying to run code from Joomla my cms here is what I get any help would be much appreciated.

Fatal error: Cannot redeclare __autoload() (previously declared in /home/emaginei/public_html/libraries/loader.php:159) in /home/emaginei/public_html/shop/app/code/core/Mage/Core/functions.php on line 77

Strict Standards: Non-static method JFactory::getDBO() should not be called statically, assuming $this from incompatible context in /home/emaginei/public_html/libraries/joomla/session/storage/database.php on line 84

Strict Standards: Non-static method JTable::getInstance() should not be called statically, assuming $this from incompatible context in /home/emaginei/public_html/libraries/joomla/session/storage/database.php on line 89

Strict Standards: Non-static method JFactory::getDBO() should not be called statically, assuming $this from incompatible context in /home/emaginei/public_html/libraries/joomla/database/table.php on line 112

Fido

15. Jan, 2009

Parky – without knowing for sure, I’d guess that there is a conflict between Magento and Joomla both implementing the __autoload “magic method” within the same scope.

For those who don’t know, __autoload is called automatically by PHP when a class is called that is not available yet. This magic method allows you to create an implementation to include/require(_once) a php file based on the name of the class being called.

I’m not sure for a solution on this off the top of my head – it depends on if there is a way to combine the autoload implementations between the two correctly of if there is a way to move the scope of one of the autoload functions so they are not interfering.

Hope this helps! (php.net will tell more on how __autoload functions!)

Nehal

14. Feb, 2009

Hi Fido,

I am newbie in magneto commerce. I wanted to know how i can make ajax call in magento commerce actually i did it through method which simply call .php file by xmlhttp request and it’s worked but real problem is i need to place them outside means on root which is not correct. I want to use standard way calling them through contoller which i tried without success. I guess real problem is with url rewriting process because of which it’s not able to locate URL or php file if i use controller method.

sana

22. Feb, 2009

Hi :)

I’m also trying to use the session intergration exemple with no success, the reply of my script is always “not connected”…

I need to test if the current user of magento is connected and in this case to collect some informations about it…

Someone can help me :(

here is my script :

/* inclusion du fichier Mage.php */
require_once ‘magento_store/app/Mage.php’;
//umask(0);

$app = Mage::app(’default’);
Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$session = Mage::getSingleton(’customer/session’, array(’name’=>’frontend’));

/* test l’utilisateur est loggé ou pas */
if ($session->isLoggedIn()) {
echo “connected”;
} else {
echo “not connected”;

}

thanks for help :)

tommy

04. Mar, 2009

Thanks for your help with this post. For what it’s worth, here’s my code using the latest Magento hacked in with wordpress:

require_once ABSPATH . “/store/app/Mage.php”;
Mage::App();
$sess = Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$cart = Mage::helper(’checkout/cart’)->getCart()->getItemsCount();
$wl = Mage::helper(’wishlist/data’)->getItemCount();
$cust = Mage::helper(’customer/data’);

echo “custid: {$cust->getCustomer()->getId()}”;
echo “cart count: {$cart}”;
echo “wishlist count: {$wl}”;

Hridaya

13. Mar, 2009

Hello,

I have to show most sold products from my magento store site to my separate own company site.

How can i run magento code outside of magento ..

Please help me if anybody have any ideas.

Thanks

Hridaya Ghimire

Crak69

24. Mar, 2009

hi,

can any1 tell me how to login from extern? i do not get a cookie or a db-insert into the db-table core_session.
so i am not logged in when changing to the shop.
i tried the following code:

require_once MAGENTO_PATH . “app/Mage.php’;
umask(0);
Mage::app();

Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$session = Mage::getSingleton(’customer/session’);
$session->login(, );

it does not work. do i need to switch some php.ini vars? what do i do wrong?
thanks

Martin Zwernemann

24. Mar, 2009

Hello,

@Crak69
try these lines and place them in a .php-file in the rootdirectory of your Magento installation. This could be a good point to start with.

isLoggedIn()) {
Mage::run();
} else {
$session->login(”your username”, “your password” ); //
$session->setCustomerAsLoggedIn($session->getCustomer());
Mage::run();
}
?>

Best regards
Martin

Martin Zwernemann

24. Mar, 2009

Sorry, the php-tags made my previous entry unreadable.

*Begin php*
//very important: don’t send any echos or chars
//check that there are no spaces above or below the php-tags
require_once ‘app/Mage.php’;
umask(0);
Mage::app();
$session = Mage::getSingleton(’customer/session’);
if ($session->isLoggedIn()) {
Mage::run();
} else {
$session->login(”your username”, “your password” ); //
$session->setCustomerAsLoggedIn($session->getCustomer());
Mage::run();
}
*End php*

Nightfly

24. Apr, 2009

Very helpful post. Thanks!

TMW

25. Apr, 2009

@Crak69: If you are trying to run the code inside another application that already specifies and starts a session, you will not have access to the Magento session handler.

Captain

05. May, 2009

Thanks Martin !
Your post was very helpful.
Do you know how to login as admin user ?

Esp

08. May, 2009

Thanks for your post, it’s very helpful, i run the magento code in the drupal site but i don’t know how to change getBaseUrl value.

indi

10. May, 2009

Hi,
I have a Magento site and a custom developed site. What I would like to to have is if a user logs into Magento the user will have access to the custom site and vice versa.

All the users will be registered on the Magento site

What would be the best way of doing this ?

Thanks in advance.

Regards,
indi

Ahsan

22. May, 2009

Hi
Thanks a lot for providing this info.awesome post

mandalousia

27. May, 2009

hello

I have successfully login my custumer from out side magento but, the problem is i can’t to test if customer is logged in, the fonction $session->isLoggedIn() dont’work.
Is every one can help me?
My code is below. even if customer logged the function $session->isLoggedIn() turn false.

require_once “catalogue/app/Mage.php”;
umask(0);
Mage::app();
Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$session = Mage::getSingleton(”customer/session”);
$session->start();
if ($session->isLoggedIn()) {
$customer = Mage::getSingleton(”customer/customer”)->load($session->getCustomerId());
echo $customer->getName().” Déconnexion“;
} else {
$layout = Mage::getSingleton(’core/layout’);
$block = $layout->createBlock(’customer/form_login’);
$block->setTemplate(’customer/form/mini.login.phtml’);
echo $block->toHtml();
}

Daniel

31. May, 2009

Nice code snippets here. I’ve been banging my head trying to do the following… get access to a customer session from the admin controller and vice versa. I’m working on a project that unifies certain customer and admin accounts…

On the customer side, this looks like the following which is supposed to login the admin user and then redirect to the admin controller.

// create the admin session
Mage::getSingleton(’core/session’, array(’name’ => ‘adminhtml’));
$user = Mage::getModel( ‘admin/user’)->loadByUsername(USERNAME);
if (Mage::getSingleton(’adminhtml/url’)->useSecretKey()) {
Mage::getSingleton(’adminhtml/url’)->renewSecretUrls();
}
$session = Mage::getSingleton(’admin/session’);
$session->setIsFirstVisit(true);
$session->setUser($user);
$session->setAcl(Mage::getResourceModel(’admin/acl’)->loadAcl());

Mage::dispatchEvent(’admin_session_user_login_success’,array(’user’=>$user));

// redirect to adminhtml controller
$request = $this->getRequest();
$request->setRouteName(’adminhtml’)
->setControllerName(’adminhtml’)
->setActionName(’index’)
->setModuleName(’admin’)
->setPathInfo()
->setDispatched (false);

// this is the correct url
$url = Mage::getSingleton(’adminhtml/url’)->getUrl();
header(’Location: ‘ . $url);
exit;

Now when I redirect, to the admin controller… the admin session I created above doesn’t persist… it deleted or something when moving from the customer to adminhtml namespacess… any ideas?

dexcs

18. Jun, 2009

How Admin Login will work:

——————
require_once ‘app/Mage.php’;
umask(0);

$app = Mage::app(’default’);

/* Init User Session */
Mage::getSingleton(’core/session’, array(’name’=>’adminhtml’));
$session = Mage::getSingleton(’admin/session’);
$session->start();

if ($session->isLoggedIn()) {
———————-

thx to all the other authors…
dexcs

shiva

19. Jun, 2009

we can’t access the customer session from out side with the above code>

As this because of magento assigns unique session file for outside folders [Magento assumes that it is an other store]

Need to look for other alternatives. You can find session file in var/session folder.

michaellehmkuhl

30. Jun, 2009

Very helpful post.

I’ve built a DIY ajax cart in Magento using this technique, and loading the checkout/cart block, it seems that a portion of the cart data (the options selected on a configurable product, to be precise) is not being passed to the block for some reason. When I go to the normal checkout/cart page in a non-ajaxy fashion, those fields show up correctly.

Tracking it down further, it seems that in the ajaxy version, the getOptionList() function in magento/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer/Configurable.php is called in the non-ajaxy rendering, but not in the ajax.

This results in $this->getOptionList() in magento/app/design/frontend/default/default/template/checkout/cart/item/default.phtml returning nothing in the ajax function, which in turn never prints out the selected options on the ajax-rendered cart.

I seem to have reached the limits of my Magento powers here.

Any ideas?

michaellehmkuhl

06. Jul, 2009

Another potential clue to my last post is that $this->getChildHtml(’totals’) on magento/app/design/frontend/default/default/template/checkout/cart.phtml doesn’t produce any output, either.

Alex

07. Jul, 2009

Just a hint in case you want to put some “custom” data into the session, here is how it works:

Mage::getSingleton(”core/session”, array(”name” => “frontend”));
$session = Mage::getSingleton(”customer/session”, array(”name”=>”frontend”));
$session->setData(”your_key”, array(1,2,3,4));

and get it with
$session->getData(”your_key”);

Cheers
Alex

Raja

21. Jul, 2009

Hi all,
i need to implement ajax call on frontend side in magento. i put the code in file /magento/app/design/frontend/default/default/layout/page.xml
mage/adminhtml/loader.js
to include loader.js same as in admin panel and write code
new Ajax.Request(’/actualidad/News/update’,{
method: ‘post’,
parameters: { ‘id’ : value }
});

in a file, but it doesn’t work.
plz help me out of this. plz provide me a sample code of use of ajax on frontend side of magento.
thnx in anticipation.

shams

21. Jul, 2009

Hi all,

i am using the following code to login to magento from the outside website. still i cant able to login to magento can any one help me oin this?

Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$session = Mage::getSingleton(’customer/session’);
$session->login($this->input->post(’email’), $this->input->post(’password’));
$session->setCustomerAsLoggedIn($session->getCustomer());
$session->start(’frontend’);

Thanks
Shams

Fido

21. Jul, 2009

Shams, you might have a conflict with starting two sessions within one page request. It looks like you are trying to integrate Magento into a site built in CodeIgniter?

You might also want to view the comments here as they have some extra code not included there. Since there have been so many Magento updates, you may want to check out the relevant files (Mage/Core/Model/Session.php and Mage/Custerom/Model/Session.php I believe) in order to see if there is other functions to try out to properly set a session.

Also check out files related to people logging in (Try following the controller code used when a user logs in to see what models Magento loads and how it uses them).

Anh

03. Aug, 2009

Thanks! Very useful!

Name

31. Aug, 2009

I checked the shopping cart quantity and it worked on my main domain. I use multi-stores on different domains and it doesn’t seem to work if I change the location of mage.php

$mageFilename = ‘../../app/Mage.php’

Do you have any other suggestions or do you know what other variables need to be changed for it to display cart contents on another domain?

kyle

31. Aug, 2009

Mage::app(’nameofwebsitesitescope’, ‘website’);

ok, i got it now :D

Miquil

13. Sep, 2009

Can it be that including the Mage.php in WordPress doesn’t work???

Name

05. Oct, 2009

Hi Guys, I am trying to loggin in magento from outside script. its working for first time when i clicked on other pages. its automatically logged out.

Please help me out.

require_once ( “../app/Mage.php” );
umask(0);
Mage::app();
Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$session = Mage::getSingleton(’customer/session’);
$session->start();
$session->logout();
if ($session->isLoggedIn()) {
try{
Mage::run();
}catch(Exception $e){
var_dump($e); die;
}
} else {
$result = $session->login($userID,$userPassword);
$session->setCustomer($session->getCustomer());
$session->setCustomerAsLoggedIn($session->getCustomer());
try{
Mage::run();
}catch(Exception $e){
var_dump($e); die;
}
}

Name

05. Oct, 2009

Hi Guys,

I am implementing SSO in our system. right now i have four system. i have main application login page. iant to generate session and cookie for magento user too. so that when user click or want to enter maganto user so user can enter into magento site without relogin into magento.

Thanks

[...] Explore Magento Another piece of code I regularly use is gives me the ability to run my own custom code outside of Magento. This can be extremely useful if you have a specialized page not within the main Magento framework. You can find detailed instructions here. [...]

amit upadhyay

31. Oct, 2009

Hello Guys Use Following code to login ito magento from extern….

if(isset($_POST['submit']))
{
require_once ( “../app/Mage.php” );
umask(0);
Mage::app(”default”);
Mage::getSingleton(”core/session”, array(”name”=>”frontend”));
$session = Mage::getSingleton(”customer/session”);

if(isset($_POST['txt_emailaddress']) && isset($_POST['txtpassword']))
{
$email=$_POST['txt_emailaddress'];
$password=$_POST['txtpassword'];

try
{
$session->login($email, $password);
}

catch(Exception $e)
{
//echo ‘Message: ‘ .$e->getMessage();
header(”Location:index.php?invalidlogin=1″);
}

if($session->isLoggedIn())
{
$session->setCustomerAsLoggedIn($session->getCustomer());
$customer = $session->getCustomer();
header(”Location:account.php”);

}else{

header(”Location:index.php?invalidlogin=1″);
}

}

}

Magento Customization

03. Nov, 2009

Nice information about magento. Great post and comments.

Erik

17. Nov, 2009

Fido thanks for a great walkthrough! This was just what I needed for a current project. Also, Amit your login snippet works like a charm. Thanks!

Ralf

02. Dec, 2009

I use this code to run the magento session in an popup but I get an error in IE7 – and only – in IE8 and other browsers it works.

The error:

Fatal error: Uncaught exception ‘Mage_Core_Model_Session_Exception’ ….

I make a popup-window from the cart and i have to use the magento session for an upload.

had anybody the same problem and a solution?
Thx!
Ralf

Jonas Thomaz de Faria

17. Dec, 2009

Nice information about magento. Great post and comments.

Perfect for me.

Foi a dica que eu estava precisando ótimo. Valeu

Subesh

21. Dec, 2009

Nice information, but i do have a good article of working with ajax in magento here.

http://subesh.com.np/2009/11/working-with-ajax-in-magento/

Evan Brassart

30. Dec, 2009

@JAMES

You just saved me a ton of head scratching.

[quote]
Found it.
Th secret to reinitializing the logged-in user’s session is to first instantiate ‘core/session’ and THEN ‘customer/session’.
So the magic lines to make the lest example work is:
. . .
Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$session = Mage::getSingleton(’customer/session’, array(’name’=>’frontend’));
[/quote]

Without the core/session the code below does not work and was Killing Me !!!

THANKS!

Kat

06. Jan, 2010

Hi, first thanks for this blog! Now regarding this solution (for including Ajax), though I can see what you’re getting at, I still can’t figure out what code goes into what file. Could you explain a bit further regarding that? Thanks a lot!!
(Just for the record, I alredy created some of my own custom modules, so I’m not a complete novice)

Leave a reply