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

In: Feeling guru|Techie Daw

25 Mar 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 which is version 1.4.0.1. The script below also implements the login() and logout() method the Magento way as well as extracting the customer data (firstname and lastname) using getCustomer() method.

<?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(!isset($_REQUEST['action'])) {
	$_REQUEST['action'] = '';
}

switch($_REQUEST['action']){
	case "login":
		try{
			// Do login request.
			// I know, there are ways to sanitize the form.
			// But for simplicity's sake, let's assume we already
			// did our homework regarding the matter.
			$login = $session->login($_POST['username'],$_POST['password']);
		}catch(Exception $e){
			// Do something for the error message
			$message = $e->getMessage();
		}

		header("location: index.php");

		break;
	case "logout":
		// Execute the logout request
		$session->logout();
		header("location: index.php");

		break;
	default:
		// If the customer is not logged in, show login form
		// else, show logout link
		if(!$session->isLoggedIn()){
		?>
			<html>
			<head>
			<title>External Page for Magento</title>
			</head>
			<body>
			<h3>Login here</h3>
			<form method="POST" action="index.php">
			Username <input type="text" name="username" size="10" />
			Password <input type="password" name="password" size="10" />
			<input type="submit" name="submit" value="login" />
			<input type="hidden" name="action" value="login" />
			</form>
			</body>
			</html>
<?php
		}else{
			$firstname = $session->getCustomer()->getData('firstname');
			$lastname = $session->getCustomer()->getData('lastname');
			echo "Welcome ".$firstname." ".$lastname."!<br>";
			echo "You're currently logged in ";
			echo "[ <a href=\"index.php?action=logout\">click here to logout</a> ]";
		}
}
?>

Just copy the whole script and save it as index.php and run the script.

About the author

Richard Feraro is a web programmer from Manila, Philippines with 13 years of solid open-source development experience using Linux, Apache, MySQL & PHP.

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

Avatar

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

March 25th, 2010 at 10:24 pm

[...] Updated ** For users of Magento version 1.4.0.1, click here Possibly related posts: (automatically generated)How to delete a quote from Magento?How to delete a [...]

Avatar

Jason REPUBLIC OF KOREA

March 31st, 2010 at 10:12 pm

Hi Richard,

Thank you very much for this helpful post!

Unfortunately, I’m running into a similar issue as Tim from the last post. Where the script works in the WordPress directory in a separate file, but when I simply call the file from my theme, I end up with a blank page. All I’m trying to do is log the user into Magento at the same time they’re logging into my website. Here’s my code:

require_once(“../unanchor/magento/app/Mage.php”);
umask(0);
Mage::app(‘default’);
Mage::getSingleton(‘core/session’, array(‘name’ => ‘frontend’));
$loggedin = Mage::getSingleton(‘customer/session’)->login($user,$pass);

Any thoughts or suggestions?

Thanks again!
Jason

Avatar

Richard Feraro UNITED STATES

March 31st, 2010 at 11:00 pm

Hello Jason! Thanks :)

If you’re getting a blank page, it means that there is an error in your code. Try setting the PHP error_reporting to ‘all’ just like what I suggested to Tim Jukes from the original post. It may provide clue to the error. Also, I believe there’s a function collision with Magento and WordPress but I haven’t tested it though.

Regarding your script, it should work well but I usually initiate the login separately like the sample below:

your script:
$session = Mage::getSingleton(?customer/session?)->login($user,$pass);

my suggestion:
$session = Mage::getSingleton(?customer/session?);
$session->login($user,$pass);

so you can reuse $session for checking the login status like $session->isLoggedIn(), this is the proper format for version 1.4.0.1.

Avatar

alain UNITED STATES

April 3rd, 2010 at 5:32 am

Thanks for your great post!
I’m using magento for an Intranet system and want to log user to magento using another CMS.
Got you script to work but can’t figure how to detect if user is logged or not in magento.
I added this in magento header.phtml to check for user login and limit access but keep getting “Not logged in”:

$session = Mage::getSingleton(“customer/session”, array(“name”=>”frontend”));
if($session->isLoggedIn())
{
echo “Logged in”;
}else{
echo “Not logged in”;
}

Any suggestions?

Thanks

Avatar

Richard Feraro PHILIPPINES

April 3rd, 2010 at 12:49 pm

Hello Alain! Thank you :)

Did you use the login() function of Magento? I think 1.4.0.1 requires that for isLoggedIn() to work. Also keep in mind that you need the Mage.php in all pages that uses the Magento functions.

If you’re running it thru localhost, please check my post regarding running Magento via localhost. Is your page capable of creating cookies when you run it?

Avatar

alain UNITED STATES

April 4th, 2010 at 9:06 am

Hi Richard,
what I don’t understand is that when I print the session it is different in the file that uses your code and on the Magento side. Your side as the customer info in it not the Magento side.
Basically have 2 different session is it the same for you?

Thanks

Avatar

Richard Feraro PHILIPPINES

April 4th, 2010 at 2:03 pm

What do you mean when you said, “Magento side”? Remember there two types of session there. The admin and the frontend creates two different types of session so basically you can’t compare the session created by your external file and whichever of the two sessions (frontend or adminhtml) you’re referring to as ‘Magento side’.

For example, my root folder is htdocs, my actual Magento files resides in ‘htdocs/magento’ folder and the finally external application that uses the Mage.php is placed in ‘htdocs/other’ folder. In this setup, when I run Magento’s frontend, it is running at http://localhost/magento/, right? This creates a session ‘frontend’ for a customer. If I run the admin page at http://localhost/magento/admin, this generates the ‘adminhtml’ session. So at this point we already have two different session and two different cookies. So by concept, if I run my external application using the Mage.php file which instantiates ‘frontend’ session depending on the getSingleton() method, I’ll be running it thru http://localhost/other which in turn generates a different customer session because it has a different cookie location. To check if this is true, look at this image and check the ‘path’ column in the firebug cookie tab. The admin has ‘/magento’ cookie path, in our example external application it will be ‘/other’.

http://mysillypointofview.files.wordpress.com/2010/03/magento-admin-login-with-cookie.png

Avatar

alain UNITED STATES

April 5th, 2010 at 12:55 am

Thanks, that’s what I though I can’t have have Magento use the Session generated by your script .
Do you have any idea how I would go to make my Magento catalog side password protected ?

Thanks

Alain

Avatar

Richard Feraro UNITED STATES

April 5th, 2010 at 6:06 pm

Is it for an external site or the actual Magento catalog page?

Avatar

Sanjoy INDIA

April 5th, 2010 at 7:46 pm

using Magento ver. 1.4.0.1, getting the following error when i try to logout the admin :

Invalid method Mage_Admin_Model_Session::logout(Array ( ) )

Any thoughts?

Avatar

Richard Feraro UNITED STATES

April 5th, 2010 at 8:16 pm

Hello Sanjoy!

Can you provide more details to your inquiry? I believe there’s more infomation found inside the logout(…) when this error occured in your page.

Thanks.

Avatar

Sanjoy INDIA

April 6th, 2010 at 7:02 pm

Well, I am sorry it does not give any thing more than that error. I am actually trying to log in to the magento admin from my own CMS application which i successfully did but was unable to find an way to log out the admin when i logged out of my CMS application , so i tried the code you had posted here, but it errors out with the exception “Invalid method Mage_Admin_Model_Session::logout(Array ( ) )”. Since the error says invalid method , i searched for the logout method in adminhtml, but didn’t get any, could this be the reason?

Avatar

Richard Feraro UNITED STATES

April 6th, 2010 at 11:01 pm

Hi Sanjoy,

I think you didn’t actually use my code above but rather created a different one to simulate an administrator logging in to an external site. I was able to recreate your error on my end using the code below:

// Show all errors
error_reporting(E_ALL);
// Include Magento application
require_once ( "path/to/your/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" => "adminhtml"));
$session = Mage::getSingleton("admin/session")->logout();

the code above produces this error:

Fatal error: Uncaught exception 'Varien_Exception' with message 'Invalid method Mage_Admin_Model_Session::logout(Array ( ) )' in path:\to\your\magento\lib\Varien\Object.php:542 Stack trace: #0 [internal function]: Varien_Object->__call('logout', Array) #1 path:\to\your\externalsite\index.php(13): Mage_Admin_Model_Session->logout() #2 {main} thrown in path:\to\your\magento\lib\Varien\Object.php on line 542

Is the error similar on your end?

Avatar

Sanjoy INDIA

April 7th, 2010 at 2:06 pm

Yes, that’s the error i am getting. I didn’t get all the details about the error because i was doing a try catch and was printing the exception only, but yes that’s what i was trying to do, i just replaced the frontend calls shown in your code to backend calls going by the comments (// “frontend” for frontend session or “adminhtml” for admin session) in in your code.

Avatar

Richard Feraro PHILIPPINES

April 11th, 2010 at 5:47 am

@Sanjoy: please refer to sonassi?s instruction where you got the code.

Avatar

Jason REPUBLIC OF KOREA

April 14th, 2010 at 9:08 am

Hi Richard,

This is slightly off-topic, but since you seem very knowledgeable I figured I’d give it a shot.

Can you use the above method to also check if there are items in the cart? Here’s what I’m trying to do:

require_once(“$magpath”);
umask(0);
Mage::app(‘default’);
Mage::getSingleton(‘core/session’, array(‘name’ => ‘frontend’));
$session = Mage::getSingleton(‘customer/session’);

if ((Mage::getSingleton(‘checkout/cart’)->getItemsCount()) > 0)
$cart = TRUE;
else
$cart = FALSE;

This isn’t working though, any thoughts?

Thanks again, your posts have been extremely helpful!
Jason

Avatar

Richard Feraro PHILIPPINES

April 14th, 2010 at 10:12 am

Hi Jason,

Checkout my comments within the code below:

// Remove the quote since this is a variable
require_once($magpath);
umask(0);
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));
// Use this as your session below
$cart_session = Mage::getSingleton("checkout/session");
// Use the $cart_session, access the quote, check item's count
// getItemsQty() = get total quantity as a whole
// getItemsCount() = get total unique quantity
if($cart_session->getQuote()->getItemsCount() > 0)
    $cart = TRUE;
else
    $cart = FALSE;

Thank you Jason for the feedback.

Avatar

stephan FRANCE

April 18th, 2010 at 3:50 pm

Hello Richard,

What a great post !

I would like to know if we can hire you :) for a custom installation with WP/Magento

My email contact: pecqhkg@gmail.com

Avatar

Richard Feraro PHILIPPINES

April 18th, 2010 at 5:01 pm

Thanks Stephan. Sent an email to you :)

Avatar

Pete UNITED KINGDOM

May 10th, 2010 at 8:23 pm

Great post!

Is there a way to extend the web API to carry out the login authentication and session creation, as I need to set this up from a non-PHP website (running asp.net)?

Cheers,

Pete

Avatar

Richard Feraro UNITED STATES

May 10th, 2010 at 10:35 pm

For non-PHP site, use the Magento Core API which utilizes SOAP and XML RPC protocols. It’s somewhat slower compared to running it in a manner I posted here in the article because of how web services work.

Avatar

Madhu INDIA

May 18th, 2010 at 12:39 pm

how do i access image from this session..right now i can get product name its quantity i have to display image and a delete button (same like my cart :) )how do i access image?

Avatar

Madhu INDIA

May 18th, 2010 at 12:48 pm

To be more specific I am trying to implement ajax add to cart…I am able to add products to cart again i have to refresh mycart widget..so i have come half way through as I have told i need to access image and a delete button.. so how do i access it?

Avatar

Richard Feraro UNITED STATES

May 21st, 2010 at 4:33 pm

Use the load() method for catalog/product model:

$product = Mage::getModel(?catalog/product?);
$product->load(3); // this could be any product ID
// get product image url, note this produces an image with a width of 265px
echo $product->getImageUrl();

Avatar

Michael UNITED STATES

August 17th, 2010 at 10:58 am

Richard, thanks so much for all the hard work, WP Mage-Enabler is a lovely plugin and all of your help on this blog is so appreciated!

I am having trouble detecting if a user is logged in (or not) from WP, the following code (yours) seems to always return false no matter what I try (Mage Enabler is working, and enabled, etc), any hints? Seems to just be a completely different session than Magento (possibly because Magento is in a subdirectory?). Thanks!

Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");
echo 'isLoggedIn? '.$session->isLoggedIn();
$helper = Mage::helper('customer');
echo 'isLoggedIn? '.$helper->isLoggedIn();

Avatar

Richard Feraro UNITED STATES

August 17th, 2010 at 8:46 pm

Hi Michael, thanks for the feedback.

May I know your Magento version? Also, try this one:

// Customer Information
$firstname = "John";
$lastname = "Smith";
$email = "johnsmith@localhost.local";
$password = "myverysecretpassword";

// Website and Store details
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();

$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId; 
$customer->setStore($store);

try {
	// If new, save customer information
	$customer->firstname = $firstname;
	$customer->lastname = $lastname;
	$customer->email = $email;
	$customer->password_hash = md5($password);
	if($customer->save()){
		echo $customer->firstname." ".$customer->lastname." information is saved!";
	}else{
		echo "An error occured while saving customer";
	}
}catch(Exception $e){
	// If customer already exists, initiate login
	if(preg_match('/Customer email already exists/', $e)){
		$customer->loadByEmail($email);
		
		$session = Mage::getSingleton('customer/session');
		$session->login($email, $password);
		
		echo $session->isLoggedIn() ? $session->getCustomer()->getName().' is online!' : 'not logged in';
	}
}

At the initial run of the script above, a new customer will be created if the email doesn’t exists in your customer database. It should show John Smith information is saved!. Refreshing the same page should run the login method and display John Smith is online! if successful, not logged in if not.

Avatar

Michael UNITED STATES

August 22nd, 2010 at 12:47 am

Richard,

The trouble is that the login is still occuring through the normal Magento login, so I never get the email passed to me. Thing is I have a topnav that changes based on the user’s logged in status, so I need to detect whether the user is logged into the magento store at /shop/ on all pages including those that site at the site root (not sure if the subdirectory thing is even relevant).

If I print_r the $session from inside WP its pretty empty, whereas doing it from inside a Magento page shows a whole ton of stuff (eg the actual customer info). So it seems to just not be pulling in the session properly…

Thanks again for all your help!

Avatar

Michael UNITED STATES

August 22nd, 2010 at 2:15 am

O sorry RIchard, I forgot to mention its Magento 1.4.1.1, thanks again!

Avatar

Richard Feraro PHILIPPINES

August 22nd, 2010 at 2:27 am

Question, are you trying to run Magento to an external site? Or using the Mage Enabler? I get confused maybe because you’re in a different thread. If yes, please confirm so I can move the whole conversation to the other post for Mage Enabler :)

Avatar

Michael UNITED STATES

August 22nd, 2010 at 9:39 pm

Sorry for not being clear, I am in fact using Mage Enabler

Avatar

Richard Feraro UNITED STATES

August 23rd, 2010 at 7:09 pm

May I see the code you’re using inside a WP page (include the filename if it’s a default file within WP?)

Avatar

Michael UNITED STATES

August 24th, 2010 at 10:41 am

Ahh, sorry Im just cluttering up your blog?feel free to delete the messed up ones!

head.php:

<?php
if (class_exists('Mage')) {
Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<title><?php wp_title( '|', true, 'right' ); bloginfo('name'); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="shortcut icon" type="image/x-icon" href="/shop/skin/frontend/default/xxx/favicon.ico" />
<!?<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />?>
<link rel="stylesheet" type="text/css" media="all" href="/shop/skin/frontend/default/xxx/css/styles.css" />
<link rel="stylesheet" type="text/css" media="all" href="/shop/skin/frontend/default/xxx/css/pluit-carousel.css" />
<link rel="stylesheet" type="text/css" media="all" href="/shop/skin/frontend/default/xxx/css/shadowbox.css" />
<link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Reenie+Beanie' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="/shop/js/prototype/prototype.js"></script>
<script type="text/javascript" src="/shop/js/prototype/validation.js"></script>
<script type="text/javascript" src="/shop/js/scriptaculous/builder.js"></script>
<script type="text/javascript" src="/shop/js/scriptaculous/effects.js"></script>
<script type="text/javascript" src="/shop/js/scriptaculous/dragdrop.js"></script>
<script type="text/javascript" src="/shop/js/scriptaculous/controls.js"></script>
<script type="text/javascript" src="/shop/js/scriptaculous/slider.js"></script>
<script type="text/javascript" src="/shop/skin/frontend/default/xxx/js/pluit-carousel.js"></script>
<script type="text/javascript" src="/shop/skin/frontend/default/xxx/js/shadowbox.js"></script>
<script type="text/javascript" src="/shop/skin/frontend/default/xxx/js/global.js"></script>
<?php wp_head(); ?>
</head>

header.php:
<div class="header-container">
<div class="top-nav-container">
<?php if (class_exists('Mage')) :
$top_nav_id = ($session->isLoggedIn()) ? 'top-nav-logged-in' : 'top-nav-logged-out';
// echo 'is?'.$session->isLoggedIn();
$helper = Mage::helper('customer');
// echo 'is?'.$helper->isLoggedIn();
endif;
wp_nav_menu( array( 'container_class' => 'top-nav links', 'theme_location' => $top_nav_id ) ); ?>
</div>
<div class="header">
<h1 class="logo"><strong><?php bloginfo('name'); ?></strong><a href="<?php echo get_option('home'); ?>" title="<?php bloginfo('name'); ?>" class="logo"><img src="<?php echo get_option('home'); ?>/shop/skin/frontend/default/xxx/images/logo.gif" alt="<?php bloginfo('name'); ?>" /></a></h1>
<?php wp_nav_menu( array( 'container_class' => 'main-nav links', 'theme_location' => 'main-nav' ) ); ?>
</div>
</div>

<body <?php body_class(); ?>>
<div id="wrapper">
<div class="page">

Avatar

Richard Feraro UNITED STATES

August 24th, 2010 at 7:39 pm

To display code, you may use [php]your-code-here[/php]

Avatar

Richard Feraro UNITED STATES

August 24th, 2010 at 7:57 pm

Is your Mage.php absolute URL working? What’s the output when you save the URL in the Mage Enabler admin plugin page?

Once you’ve checked that the needed parameter (URL) of the plugin is indeed correct, try adding the code below inside one of your theme files. It should show Mage and Varien_Autoload in the list.

<?php print_r(get_declared_classes()); ?>

Avatar

Michael UNITED STATES

August 25th, 2010 at 8:49 am

Mage Enabler is definitely working well (thanks again!) as later on that page I have a little scrollbar thing that pulls out a bunch of prodcuts, which has been working flawlessly from day one.?

Both Mage and Varien_Autoload are listed in the declared classes, so still no idea why its giving me trouble?weird right?!

Avatar

Richard Feraro UNITED STATES

August 25th, 2010 at 3:19 pm

Your scripts’ logic in checking whether a user is online or not seems okay and Mage’s session is running in your page. How about your login script? May I see it?

Avatar

Michael UNITED STATES

August 25th, 2010 at 10:00 pm

Hmm, I am actually just using Magento’s login. So the user logs in at domain.com/shop/customer/account/login but I was hoping that session could carry over to all pages including those at domain.com/ (/shop is Magento root folder). That the problem (I still dont get why)?

Avatar

Richard Feraro UNITED STATES

August 25th, 2010 at 10:42 pm

I see, now I understand. Mage Enabler, like what its description says, only runs the Magento’s session inside your WordPress. Magento’s session means the Mage object (Mage and Varien_Autoload), the one you see when you ran get_declared_classes() so it’s perfectly working on your end. No wonder you say it isn’t working because you didn’t do any programming at all for the login.

Try reading some of the info here. It may enlighten you on how to do it.

Avatar

Michael UNITED STATES

August 26th, 2010 at 1:34 am

Aha, except mine would be more like the opposite of that post of yours. I dont even really need people to be able to login to WP, just detect their logged in status in Magento. If I were to have to go through WP it would also mean making the user registration mirror from Magento to WP, which sounds like a lot of work. Am I missing something here? Any kind of workaround you can think of?

Thanks again for your help

Avatar

Richard Feraro PHILIPPINES

August 26th, 2010 at 1:50 am

You can’t detect from WordPress who’s online in Magento because the two has different cookie session path. Your shop’s cookie path is in ‘/shop’ while WordPress is in the www root ‘/’. The purpose of Mage Enabler is to do the manipulation of session (i.e. login, registration, product query etc.) within WordPress thru Mage object, not the other way around.

Avatar

Richard Feraro PHILIPPINES

August 26th, 2010 at 1:51 am

The login script must be executed within WordPress and then pass thru Mage session.

Avatar

Michael UNITED STATES

August 26th, 2010 at 7:35 am

Richard, thanks so much for all your help. What I ended up doing, now that you helped me figure out the problem was to add an event hook Observer to Magento for login / logout and have this set a custom cookie that WP then checks for later. Works pretty well!

Thanks again for all your help

Avatar

rajputvipul88 UNITED STATES

September 14th, 2010 at 6:42 am

great work !!! help lot …

Avatar

Richard Feraro UNITED STATES

September 14th, 2010 at 3:21 pm

Thanks :) Keep on reading.

Avatar

ken CHINA

November 7th, 2010 at 8:44 pm

Great post, Richard.

And I have a question about the admin session. My objective is running an admin action. So I create an admin session whith following code:
Mage::getSingleton(“core/session”, array(“name” => “adminhtml”));
$session = Mage::getSingleton(“admin/session”);
$session->login($username, $password);

Then I used CURL to access that action, the CURL opt is as follows:
$defaults = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => TRUE,
CURLOPT_COOKIESESSION => TRUE,
CURLOPT_COOKIE => “adminhtml=”.$sessionId,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 20,
CURLOPT_USERAGENT => “Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12″
);

The truth is I can not get any result from CURL but a timeout. If I disable the CURLOPT_COOKIE, but the result is the conect of login page. So do you know how to run a backend action or visit a backend page content? Thanks in advance.

Avatar

Richard Feraro PHILIPPINES

November 8th, 2010 at 12:24 pm

Thanks Ken.

I’m just wondering, why would you use CURL for that purpose when you can directly access it via Mage object?

Mage::getSingleton('core/session', array('name'=>'adminhtml'));
$session = Mage::getSingleton('admin/session');
$session->login('<username>','<password>');
$session->start();

Avatar

franmagdalena

November 22nd, 2010 at 10:50 pm

Hi Richard.

do you know where I can find a full api reference for mage::app, Mage::getModel, etc… what parameter I can use…

Thanks

Avatar

Richard Feraro UNITED STATES

November 22nd, 2010 at 11:22 pm

Hello there :)

You can find it in the Magento docs http://docs.magentocommerce.com/

Avatar

Barry NEW ZEALAND

December 3rd, 2010 at 10:12 am

Hiya Richard,

Thanks for your excellent post :)

In my case I’m running a CMS and have magento installed in /store. My login form is handled by the CMS outside of Magento. Im able to login and start the Mage session using your code.

But when I visit /store/ Magento doesn’t seem to pick up the session that I create above. Do you know how to make Magento recognise that I’ve logged in a customer externally?

Many Thanks,

Barry

Avatar

Richard Feraro UNITED STATES

December 6th, 2010 at 5:00 pm

Hello Barry :)

It’s a limitation of cookie based authentication. PHP sessions can’t share between domains because they use cookies. What you can do is pass the SID parameter through the URL to your shop like the one below:

<a href="http://www.your.domain.com/magento/?SID=<?php echo session_id(); ?>">go to store</a>

Avatar

Lukas CZECH REPUBLIC

January 12th, 2011 at 9:35 am

Hi,

I tried delete all session: session_destroy();

Avatar

Richard Feraro PHILIPPINES

January 12th, 2011 at 11:58 am

What for?

Avatar

Christoph GERMANY

January 28th, 2011 at 7:18 am

Hey Richard,
your site seems to be a big black hole for everybody who has question about magento :) Thank you for all this stuff i read here. But i still have a problem: i try to login as a customer from another site via SOAP. I got some code from http://todd.be/notes/magento-customer-login-api , but i am not able to get it work. I think it has something to do with the frontend session-id. IsLoggedIn always returns false and if i try to login i get this login/password error.
The api-file is the same as thttp://todd.be/notes/magento-customer-login-api and my php file with the SOAP stuff looks like this:

login(‘customApiUser’, ‘customApiUser’);
$loginData = array(
‘email’ => ‘mail@mail.mail’,
‘password’ => ‘password’
);
var_dump($proxy->call($sessionID, ‘customer.login’, array($loginData)));
$proxy->endSession($sessionID);
?>

Some other custom functions of the api i wrote are working, so i think the config.xml and so on are ok.

Many Thanks for help
Greetings

Avatar

Richard Feraro UNITED STATES

January 28th, 2011 at 10:09 am

Hi Christoph :)

The only reason that the api would not return the active customer session is when you pass an invalid PHPSESSID. I would suggest doing the steps I mentioned in this post if you have local access to the Magento instance. The SOAP API should always be a second option since its kinda slow compared to manipulating the Mage object directly.

Regards:)

Avatar

Christoph GERMANY

January 28th, 2011 at 7:43 pm

Oh, i didn’t thought about it in that way. I was so obsessed by creating the SOAP version, but of course its more easy to use the Magento code directly. Thank you for opening my mind and eyes :) Everything works fine.

What do you think about setting a cookie (path: magento root folder) with the current $_COOKIE["frontend"] of your index.php to place your index.php anywhere else but not in the magento root folder. If i don’t do this, i am logged in via your index.php but not via the index.php of the magento frontend because of different frontend session ids.

Anyway, thanks for your help. I can finish this peace of work i spent more than 3 days.

Greetings to USA or Philippines or wherever :)

Avatar

Richard Feraro

January 30th, 2011 at 3:45 am

You may pass the PHPSESSID in the URL from Magento to your external site or the other way around for the two apps to share the same session.

Regards

Avatar

Nabeel PAKISTAN

February 5th, 2011 at 5:24 pm

Hi Richard,

I have a problem with running the site on localhost…. just homepage is working…. but inner pages and admin section is not working… it says… 404 file not found….. Can you help?

Thanks

Avatar

Richard Feraro PHILIPPINES

February 6th, 2011 at 7:22 pm

Hello Nabeel,

Do you have mod_rewrite module enabled in your Apache setup?

Avatar

Prasenjit Aluni INDIA

March 16th, 2011 at 9:47 pm

Sir,
May U help me slove my problem..

This code properly works for login from outside of magento in IE7 but not for mozilla and chrome

'frontend'));
	$session = Mage::getSingleton('customer/session');
	$session->start();

	$login="nowstar@gmail.com";
	$pass="nowstar";	

	
	try
	{

		$login="nowstar@gmail.com";
		$pass="nowstar";
		echo "LOGIN TEST1 user Name: ".$login."password: ".$pass;		
		$session->login($login,$pass);
		$session->setCustomerAsLoggedIn($session->getCustomer());	
		$customer = Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId());			//Load the customer modules
		$customer->loadByEmail($login);		//Get customer attribbutes
		$session->start();	
		echo "Successfully Login ";
		// Do the stuff you need to when user authenticates		
	}
	catch (Exception $e)
	{
		$key ="authenticate=N";
	}	
?>

Thanks in advance

From
Prasenjit

Avatar

Richard Feraro PHILIPPINES

March 18th, 2011 at 12:30 pm

Hi Prasenjit Aluni,

You have a LOT of unnecessary code added there. Refer to this comment instead.

Avatar

Ashish INDIA

April 15th, 2011 at 2:55 pm

Is same can be done for version 1.5.0.1??
I tried the above code but it didnot work for me.

Avatar

Richard Feraro UNITED STATES

April 15th, 2011 at 5:33 pm

Yes, it should be the same. How did you do it?

Avatar

Ashish INDIA

April 15th, 2011 at 7:39 pm

My magento is installed in store directory adn other CMS is in root directory And i want when admin logs into the admin section of CMS he is also loggen in to Magento

I tried with the this code to login to the admin panel

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

if(!isset($_REQUEST['action'])) {
$_REQUEST['action'] = ”;
}

switch($_REQUEST['action']){
case “login”:
try{

$login = $session->login($_POST['username'],$_POST['password']);
}catch(Exception $e){

$message = $e->getMessage();
}
header(“location: index.php”);
break;
case “logout”:

$session->logout();
header(“location: index.php”);

break;
default:
if(!$session->isLoggedIn()){
?>

External Page for Magento

Login here

Username
Password

getCustomer()->getData(‘firstname’);
$lastname = $session->getCustomer()->getData(‘lastname’);
echo “Welcome “.$firstname.” “.$lastname.”!”;
echo “You’re currently logged in “;
echo “[ click here to logout ]“;
}
}

?>
every time i post the form to login I get the Login form back.

And if i change
$session = Mage::getSingleton(“core/session”);

I recieve an error
Fatal error: Uncaught exception ‘Varien_Exception’ with message ‘Invalid method Mage_Core_Model_Session::isLoggedIn(Array ( ) )’ in E:\xampp\htdocs\goo2o.com\store\lib\Varien\Object.php:569 Stack trace: #0 [internal function]: Varien_Object->__call(‘isLoggedIn’, Array) #1 E:\xampp\htdocs\goo2o.com\index.php(30): Mage_Core_Model_Session->isLoggedIn() #2 {main} thrown in E:\xampp\htdocs\goo2o.com\store\lib\Varien\Object.php on line 569

Avatar

Richard Feraro UNITED STATES

April 15th, 2011 at 8:14 pm

Your script show that you’re using adminhtml as cookie name instead of frontend. Follow the post above, check line 11. You’ll see that I didn’t use adminhtml. You’re getting the Invalid method Mage_Core_Model_Session::isLoggedIn... error because isLoggedIn()is used together with frontend. You can use [php]your code here[/php] to post your PHP codes.

Avatar

Daniel NETHERLANDS

May 22nd, 2011 at 7:10 pm

Thanks! works like a charm!

Avatar

Richard Feraro

May 23rd, 2011 at 6:27 am

Thanks too :-)

Avatar

elTino GERMANY

July 1st, 2011 at 5:10 pm

Hi Richard, not sure how you can help me on this one, you surely have lot of experience on this and I´m a bit desperate because my problem seems to be a sylly thing that I just cant work out… We have a multisite and multilingual Magento CE 1.4.1 installation. My client has an static site that whats to add to the Magento platform to control stock and a better ecommerce experience . This static site has so so many pages, and it´d be really long to create them on CMS on Magento, so my idea is to set a folder on the root, put that site there. Then on Magento build the theme simulating the static site and just use the cart and checkout part that Magento offers… So I have a page on the static site that takes you to the shopping cart of MAgento… (I had to dig pretty deep on this for long but got it to work). I use a php “home-made” module created that uses the $_POST['sku-entry] and spits out a URL containg the ‘produtc’ and ‘qty’ variables needed to add the product on the Magento cart. Until here all good…
What I explained above got it to work, but only when the final URL taking you to the shop is like this: domain.com/checkout/cart/add?product=…&qty=…

The problem is that this static website isnt truly one, there are 5 copies but on different languages.
So I set up on Magento: a website, store, and 5 store views…. Here it´s the complications…

If I want to take the user to a particular store-view like (spanish), i tried that the final URL is like this:
domain.com /ES/checkout/cart/add?product=…&qty=…

On Magento Store configuration, if I change the “unsecure web url” on the store view level to: “domain.com/ES/” to get it to work… But this just goes to the 404 CMS error page… Doesnt even load the cart page

I dnt know if I explain myself…

I´m a bit desperate because I know this must be a silly thing to do and after all I achived above I get really frustrated that I cant get it to work…

Can you please guide me on this one?, tell me if i´m on the right path, or if what I want to do it´s simply no possible. What other variable I need to pass on to get a product added on the cart of a particular store view, from an external page…

In any case, thanx.

Tino

Avatar

Freddy UNITED STATES

August 28th, 2011 at 11:52 pm

Hi Richard,

I just created a Google Chrome Web App for my magento store. I would like to create a URL that includes username and password of the customer. Of course I will have to define variables in the Web App, so the customer will go to options and specify username and password, and then, every time the customer clicks the icon of my application, the store should open with the user logged in already.

How should I structure the URL?

Avatar

roger UNITED STATES

September 1st, 2011 at 7:09 am

Wow, this was a fantastic push in the right direction for me!

One problem, though:
“echo $session->isLoggedIn() ? $session->getCustomer()->getName().’ is online!’ : ‘not logged in';”

returns “xxxxx yyy is online!”

but when I comment out the “echo” line and do a redirect to the front page of the store, the “Log In” button is there and I cant access customer account/details until I log in at the “store/customer/account/login/” page.

Any idea of what I’m doing wrong?

Avatar

Richard Feraro PHILIPPINES

September 1st, 2011 at 8:48 pm

What have you done so far?

Avatar

roger UNITED STATES

September 1st, 2011 at 10:12 pm

require_once ‘/var/www/html/anewltp/store/app/Mage.php';
umask(0);
Mage::app(‘default’);

$customer = Mage::getModel(‘customer/customer’);
//$customer = new Mage_Customer_Model_Customer();
$password = ‘123456’;
$email = ‘aaaaakkkkk@xxxxxx.com';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
//Zend_Debug::dump($customer->debug()); exit;
if(!$customer->getId()) {
$customer->setEmail($email);
$customer->setFirstname(‘Fnamedbtest’);
$customer->setLastname(‘Lnamedbtest’);
$customer->setData( ‘group_id’, 5 );
$customer->setPassword($password);
}
try {
//$customer->save();
$customer->setConfirmation(null);
$customer->save();
/// //Make a “login” of new customer
///Mage::getSingleton(‘customer/session’)->loginById($customer->getId());
Mage::getSingleton(“core/session”, array(“name” => “frontend”));
$session = Mage::getSingleton(“customer/session”);
try{
$session->login($email, $password);
echo $session->isLoggedIn() ? $session->getCustomer()->getName().’ is online!’ : ‘not logged in';
die();
}catch(Exception $e){
// Do something for the error message
$message = $e->getMessage();
//die($message);
}
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
//die();
}

/*
Mage::getSingleton(‘core/session’, array(‘name’ => ‘frontend’));
$name=”offer_email”;
$value=$_SESSION[offer_email];
Mage::getModel(‘core/cookie’)->set($name, $value, $period, $path, $domain, $secure, $httponly);
*/
//header(“Location: http://www.xxxxx.com/store/checkout/cart/add?product=10&qty=2&options2=5&aw_sarp_subscription_type=1“);
header(“Location: http://www.xxxxx.com/store“);
exit;

Avatar

Russ Meder UNITED STATES

September 3rd, 2011 at 5:59 am

I have followed your blog post on admin login for Magento 1.4.1 and still am unable to get it to work on certain pc’s. I need help. :)

Avatar

Christian GERMANY

September 12th, 2011 at 9:33 pm

Hi Richard,

thank you for your great article and the work you spent in all these useful replies.

I run Magento 1.5.1.0 with TYPO3 4.5.5 and want to display login status and number of items in chart within the CMS part by writing a small TYPO3 Extension. I already fixed the problem with the cookie path (Magento runs in a folder [i]shop/[/i] inside of the TYPO3 root) and changed the session name to ‘frontend’, but isLoggedIn() never returns a true.
When I use the same code in an extra file in the TYPO3 root, everything works as it should:

$mageFilename = 'shop/app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();

$magentoSession = Mage::getSingleton('core/session', array('name'=&gt;'frontend'));
$customer = Mage::helper('customer');
$cart = Mage::helper('checkout/cart')-&gt;getCart();

echo 'Logged in: ' . ($customer-&gt;isLoggedIn() ? 'Yes' : 'No');
echo '&lt;br /&gt;';
echo 'Items in basket: ' . $cart-&gt;getItemsCount();

The problem seems to be that TYPO3 already starts a php session so Magento cannot init it as it normally does (there can be found many:

if (isset($_SESSION)) {
            return $this;
}

in the Mage_Core_Model_Session_… Classes
Do you have a hint for me how to get my code running? Unsetting $_SESSION before calling Mage::getSingleton(‘core/session’, …) or deleting the checks mentioned above where not successful. Is there a Mage method that forces session initialisation?

Thank you in advance
Christian

Avatar

Richard Feraro PHILIPPINES

September 14th, 2011 at 11:56 pm

Try moving the getsingleton code to a different file since it creates a cookie which causes the header sent error.

Avatar

amit INDIA

September 15th, 2011 at 7:05 pm

hi,
very very nice blog.Such a nice blogger and expert also.
Can You Able to answer my qusetion please,
Q)–> I want to use magento for customer signup page from an external website or a php page as you have been discuss with your earlier blogs,and it should also maintain the session throughout from external website to magento,so it is possible to integrate the signup page of an external website and magento’s customer sign up page.Thanks!
Keep Writing Blogs ,Richard. : )

Avatar

Richard Feraro PHILIPPINES

September 15th, 2011 at 9:55 pm

Yes, I have a post on how to create a magento customer account from an external site.

Avatar

amit INDIA

September 16th, 2011 at 2:39 pm

Actually i am using magento with a third party integration with an external site,here i want is that how can i fetch the magento customer login session (during customer login in magento),and then i use that session id with my external site integration,so is it possible to fetch the sessioid of customer after login and where sholud i get that value of session.

Avatar

Sajid PAKISTAN

October 5th, 2011 at 1:59 am

Richard

thanks for this informative post.

i am working on automating admin login from thirdparty application. everything on code level is working fine. $session->isLoggedin returning true but magento application isnt picking session info and redirects to login page. SID trick isnt working nor placing thirdparty application in magento directory to overcome domain issue.


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

if (Mage::getSingleton('adminhtml/url')->useSecretKey()) {
Mage::getSingleton('adminhtml/url')->renewSecretUrls();
}

$session = Mage::getSingleton('admin/session');

$session->login ( $username, $password);

$user = Mage::getModel('admin/user')->loadByUsername($username);
$session->setUser($user);
$session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
$session->start();
Mage::dispatchEvent('admin_session_user_login_success',array('user'=>$user));

if ($session->isLoggedIn()) {

$request = Mage::app()->getRequest();
$request->setRouteName('adminhtml')
->setControllerName('adminhtml')
->setActionName('index')
->setModuleName('admin')
->setPathInfo()
->setDispatched(false);

$url = Mage::getSingleton('adminhtml/url')->getUrl();

header('Location: ' . $url);
}

Avatar

ccheck UNITED STATES

October 8th, 2011 at 12:58 am

Hi Richard,

I was wondering about how COMPARE PRODUCTS and RECENTLY VIEWED works when implementing on External site.

a) Are the related items stored in a SESSION or in the DATABASE?
b)How do I access and display what is currently in COMPARE PRODUCTS and RECENTLY VIEWED on external site?
c) And for COMPARE PRODUCTS I am getting different results when a user is logged in vs logged out…. Is this normal?

See my code below…

RECENTLY VIEWED CODE

$recent = Mage::getModel('review/review')->getProductCollection()->count();
$rec = Mage::getModel('review/review')->getProductCollection();

foreach($rec AS $item)
{
  // DISPLAY ITEMS IN RECENTLY VIEWED
}

COMPARE PRODUCTS CODE

$compare = Mage::helper('catalog/product_compare')->getItemCount();
$comp = Mage::helper('catalog/product_compare')->getItemCollection();

foreach($comp AS $item)
{
  // DISPLAY ITEMS IN COMPARE PRODUCTS
}

Thanks in advance,
Pres

Avatar

Sajid PAKISTAN

October 22nd, 2011 at 12:35 am

i noticed one thing

if you application / script has already started session before loggin into magento then magento application wont recognize your session when you redirected to the store.

Avatar

Richard Feraro

October 22nd, 2011 at 12:37 am

It depends on how you setup your cookie domain of the store.

Avatar

xomero MEXICO

January 6th, 2012 at 9:01 am

Does any one knows if this still working in Magento 1.6.1.0? I’m trying this code and is not working:


require_once ($_SERVER['DOCUMENT_ROOT']."/store/app/Mage.php" );
umask(0);
Mage::app('store2');

Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");
if(!$session->isLoggedIn()){
	//print_r($session);
	//--redirect stuff here
	exit;
}

Avatar

Richard Feraro

January 7th, 2012 at 12:46 pm

Yes it does. Try running the code below and post the output here:
< ?php print_r(get_declared_classes()); ?>

Avatar

Vikas INDIA

January 23rd, 2012 at 3:22 pm

Hello Richard,

Thanks for very useful posts and sharing the knowledge.

I am facing a problem to run the following code with the Magento 1.6.1.0 :

ini_set('error_reporting', 'all');
/**
 * @author MESMERiZE
 * @copyright 2012
 */

require_once ("magento/magento/app/Mage.php" );
umask(0);
Mage::app('default');

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

if(!$session->isLoggedIn()){
	print_r($session);
	//--redirect stuff here
	exit;
}

I trying on localhost.

 <?php print_r(get_declared_classes()); ?> 

For this code I have the following output:


Array
(
    [0] => stdClass
    [1] => Exception
    [2] => ErrorException
    [3] => COMPersistHelper
    [4] => com_exception
    [5] => com_safearray_proxy
    [6] => variant
    [7] => com
    [8] => dotnet
    [9] => ReflectionException
    [10] => Reflection
    [11] => ReflectionFunctionAbstract
    [12] => ReflectionFunction
    [13] => ReflectionParameter
    [14] => ReflectionMethod
    [15] => ReflectionClass
    [16] => ReflectionObject
    [17] => ReflectionProperty
    [18] => ReflectionExtension
    [19] => DateTime
    [20] => DateTimeZone
    [21] => LibXMLError
    [22] => __PHP_Incomplete_Class
    [23] => php_user_filter
    [24] => Directory
    [25] => SimpleXMLElement
    [26] => DOMException
    [27] => DOMStringList
    [28] => DOMNameList
    [29] => DOMImplementationList
    [30] => DOMImplementationSource
    [31] => DOMImplementation
    [32] => DOMNode
    [33] => DOMNameSpaceNode
    [34] => DOMDocumentFragment
    [35] => DOMDocument
    [36] => DOMNodeList
    [37] => DOMNamedNodeMap
    [38] => DOMCharacterData
    [39] => DOMAttr
    [40] => DOMElement
    [41] => DOMText
    [42] => DOMComment
    [43] => DOMTypeinfo
    [44] => DOMUserDataHandler
    [45] => DOMDomError
    [46] => DOMErrorHandler
    [47] => DOMLocator
    [48] => DOMConfiguration
    [49] => DOMCdataSection
    [50] => DOMDocumentType
    [51] => DOMNotation
    [52] => DOMEntity
    [53] => DOMEntityReference
    [54] => DOMProcessingInstruction
    [55] => DOMStringExtend
    [56] => DOMXPath
    [57] => RecursiveIteratorIterator
    [58] => IteratorIterator
    [59] => FilterIterator
    [60] => RecursiveFilterIterator
    [61] => ParentIterator
    [62] => LimitIterator
    [63] => CachingIterator
    [64] => RecursiveCachingIterator
    [65] => NoRewindIterator
    [66] => AppendIterator
    [67] => InfiniteIterator
    [68] => RegexIterator
    [69] => RecursiveRegexIterator
    [70] => EmptyIterator
    [71] => ArrayObject
    [72] => ArrayIterator
    [73] => RecursiveArrayIterator
    [74] => SplFileInfo
    [75] => DirectoryIterator
    [76] => RecursiveDirectoryIterator
    [77] => SplFileObject
    [78] => SplTempFileObject
    [79] => SimpleXMLIterator
    [80] => LogicException
    [81] => BadFunctionCallException
    [82] => BadMethodCallException
    [83] => DomainException
    [84] => InvalidArgumentException
    [85] => LengthException
    [86] => OutOfRangeException
    [87] => RuntimeException
    [88] => OutOfBoundsException
    [89] => OverflowException
    [90] => RangeException
    [91] => UnderflowException
    [92] => UnexpectedValueException
    [93] => SplObjectStorage
    [94] => XMLReader
    [95] => XMLWriter
    [96] => SWFShape
    [97] => SWFFill
    [98] => SWFGradient
    [99] => SWFBitmap
    [100] => SWFText
    [101] => SWFTextField
    [102] => SWFFont
    [103] => SWFDisplayItem
    [104] => SWFMovie
    [105] => SWFButton
    [106] => SWFAction
    [107] => SWFMorph
    [108] => SWFSprite
    [109] => SWFSound
    [110] => SWFFontChar
    [111] => SWFSoundInstance
    [112] => SWFVideoStream
    [113] => SWFPrebuiltClip
    [114] => mysqli_sql_exception
    [115] => mysqli_driver
    [116] => mysqli
    [117] => mysqli_warning
    [118] => mysqli_result
    [119] => mysqli_stmt
    [120] => PDFlibException
    [121] => PDFlib
    [122] => PDOException
    [123] => PDO
    [124] => PDOStatement
    [125] => PDORow
    [126] => SoapClient
    [127] => SoapVar
    [128] => SoapServer
    [129] => SoapFault
    [130] => SoapParam
    [131] => SoapHeader
    [132] => SQLiteDatabase
    [133] => SQLiteResult
    [134] => SQLiteUnbuffered
    [135] => SQLiteException
    [136] => XSLTProcessor
    [137] => ZipArchive
    [138] => paradox_db
    [139] => paradox_db
    [140] => ZipArchive
    [141] => XSLTProcessor
    [142] => SQLiteException
    [143] => SQLiteUnbuffered
    [144] => SQLiteResult
    [145] => SQLiteDatabase
    [146] => SoapHeader
    [147] => SoapParam
    [148] => SoapFault
    [149] => SoapServer
    [150] => SoapVar
    [151] => SoapClient
    [152] => PDORow
    [153] => PDOStatement
    [154] => PDO
    [155] => PDOException
    [156] => PDFlib
    [157] => PDFlibException
    [158] => mysqli_stmt
    [159] => mysqli_result
    [160] => mysqli_warning
    [161] => mysqli
    [162] => mysqli_driver
    [163] => mysqli_sql_exception
    [164] => SWFPrebuiltClip
    [165] => SWFVideoStream
    [166] => SWFSoundInstance
    [167] => SWFFontChar
    [168] => SWFSound
    [169] => SWFSprite
    [170] => SWFMorph
    [171] => SWFAction
    [172] => SWFButton
    [173] => SWFMovie
    [174] => SWFDisplayItem
    [175] => SWFFont
    [176] => SWFTextField
    [177] => SWFText
    [178] => SWFBitmap
    [179] => SWFGradient
    [180] => SWFFill
    [181] => SWFShape
    [182] => XMLWriter
    [183] => XMLReader
    [184] => SplObjectStorage
    [185] => UnexpectedValueException
    [186] => UnderflowException
    [187] => RangeException
    [188] => OverflowException
    [189] => OutOfBoundsException
    [190] => RuntimeException
    [191] => OutOfRangeException
    [192] => LengthException
    [193] => InvalidArgumentException
    [194] => DomainException
    [195] => BadMethodCallException
    [196] => BadFunctionCallException
    [197] => LogicException
    [198] => SimpleXMLIterator
    [199] => SplTempFileObject
    [200] => SplFileObject
    [201] => RecursiveDirectoryIterator
    [202] => DirectoryIterator
    [203] => SplFileInfo
    [204] => RecursiveArrayIterator
    [205] => ArrayIterator
    [206] => ArrayObject
    [207] => EmptyIterator
    [208] => RecursiveRegexIterator
    [209] => RegexIterator
    [210] => InfiniteIterator
    [211] => AppendIterator
    [212] => NoRewindIterator
    [213] => RecursiveCachingIterator
    [214] => CachingIterator
    [215] => LimitIterator
    [216] => ParentIterator
    [217] => RecursiveFilterIterator
    [218] => FilterIterator
    [219] => IteratorIterator
    [220] => RecursiveIteratorIterator
    [221] => DOMXPath
    [222] => DOMStringExtend
    [223] => DOMProcessingInstruction
    [224] => DOMEntityReference
    [225] => DOMEntity
    [226] => DOMNotation
    [227] => DOMDocumentType
    [228] => DOMCdataSection
    [229] => DOMConfiguration
    [230] => DOMLocator
    [231] => DOMErrorHandler
    [232] => DOMDomError
    [233] => DOMUserDataHandler
    [234] => DOMTypeinfo
    [235] => DOMComment
    [236] => DOMText
    [237] => DOMElement
    [238] => DOMAttr
    [239] => DOMCharacterData
    [240] => DOMNamedNodeMap
    [241] => DOMNodeList
    [242] => DOMDocument
    [243] => DOMDocumentFragment
    [244] => DOMNameSpaceNode
    [245] => DOMNode
    [246] => DOMImplementation
    [247] => DOMImplementationSource
    [248] => DOMImplementationList
    [249] => DOMNameList
    [250] => DOMStringList
    [251] => DOMException
    [252] => SimpleXMLElement
    [253] => Directory
    [254] => php_user_filter
    [255] => __PHP_Incomplete_Class
    [256] => LibXMLError
    [257] => DateTimeZone
    [258] => DateTime
    [259] => ReflectionExtension
    [260] => ReflectionProperty
    [261] => ReflectionObject
    [262] => ReflectionClass
    [263] => ReflectionMethod
    [264] => ReflectionParameter
    [265] => ReflectionFunction
    [266] => ReflectionFunctionAbstract
    [267] => Reflection
    [268] => ReflectionException
    [269] => dotnet
    [270] => com
    [271] => variant
    [272] => com_safearray_proxy
    [273] => com_exception
    [274] => COMPersistHelper
    [275] => ErrorException
    [276] => Exception
    [277] => stdClass
    [278] => Mage
    [279] => Varien_Autoload
    [280] => Varien_Profiler
    [281] => Mage_Core_Model_App
    [282] => Varien_Event_Collection
    [283] => Varien_Event_Observer_Collection
    [284] => Varien_Simplexml_Config
    [285] => Mage_Core_Model_Config_Base
    [286] => Mage_Core_Model_Config
    [287] => Varien_Object
    [288] => Mage_Core_Model_Config_Options
    [289] => Mage_Core_Model_Locale
    [290] => Varien_Simplexml_Element
    [291] => Mage_Core_Model_Config_Element
    [292] => Zend_Cache
    [293] => Zend_Cache_Backend
    [294] => Zend_Cache_Backend_File
    [295] => Zend_Cache_Core
    [296] => Mage_Core_Model_Abstract
    [297] => Mage_Core_Model_Website
    [298] => Mage_Core_Model_Resource_Abstract
    [299] => Mage_Core_Model_Mysql4_Abstract
    [300] => Mage_Core_Model_Mysql4_Website
    [301] => Mage_Core_Model_Resource
    [302] => Varien_Data_Collection
    [303] => Varien_Data_Collection_Db
    [304] => Mage_Core_Model_Mysql4_Collection_Abstract
    [305] => Mage_Core_Model_Mysql4_Website_Collection
    [306] => Mage_Core_Model_Resource_Type_Abstract
    [307] => Mage_Core_Model_Resource_Type_Db
    [308] => Mage_Core_Model_Resource_Type_Db_Pdo_Mysql
    [309] => Zend_Db_Adapter_Abstract
    [310] => Zend_Db_Adapter_Pdo_Abstract
    [311] => Zend_Db_Adapter_Pdo_Mysql
    [312] => Varien_Db_Adapter_Pdo_Mysql
    [313] => Zend_Db
    [314] => Zend_Db_Profiler
    [315] => Zend_Db_Statement
    [316] => Zend_Db_Statement_Pdo
    [317] => Zend_Db_Select
    [318] => Varien_Db_Select
    [319] => Mage_Core_Model_Store_Group
    [320] => Mage_Core_Model_Mysql4_Store_Group
    [321] => Mage_Core_Model_Mysql4_Store_Group_Collection
    [322] => Mage_Core_Model_Store
    [323] => Mage_Core_Model_Mysql4_Store
    [324] => Mage_Core_Model_Mysql4_Store_Collection
    [325] => Zend_Db_Expr
    [326] => Mage_Core_Model_Cookie
    [327] => Zend_Controller_Request_Abstract
    [328] => Zend_Controller_Request_Http
    [329] => Mage_Core_Controller_Request_Http
    [330] => Mage_Core_Model_App_Area
    [331] => Mage_Core_Model_Session_Abstract_Varien
    [332] => Mage_Core_Model_Session_Abstract
    [333] => Mage_Core_Model_Session
    [334] => Mage_Core_Controller_Varien_Front
    [335] => Mage_Core_Controller_Varien_Router_Abstract
    [336] => Mage_Core_Controller_Varien_Router_Standard
    [337] => Mage_Core_Controller_Varien_Router_Admin
    [338] => Varien_Event
    [339] => Varien_Event_Observer
    [340] => Mage_Cms_Controller_Router
    [341] => Mage_Core_Controller_Varien_Router_Default
    [342] => Mage_Core_Helper_Abstract
    [343] => Mage_Core_Helper_Http
    [344] => Mage_Customer_Model_Session
    [345] => Mage_Core_Model_Config_Data
    [346] => Mage_Customer_Model_Config_Share
)

Please let me know if this is possible to achieve this or not.

Thanks for your time in advance to read my query and send me answer.

Avatar

Vikas INDIA

January 23rd, 2012 at 9:55 pm

Have you find anything. Please let me klnow

Avatar

Richard Feraro

January 26th, 2012 at 2:57 pm

Your code is correct. What are you trying to do with it?

Avatar

Vikas INDIA

January 27th, 2012 at 1:01 pm

Hello Richard,

Thanks for your reply. Let me explain what I am doing:

1) I had installed magento in a subfolder- “magento”. Then I had added the above code in test.php outside above said subfolder. I am not able to access the session or user status whether he is logged in or not. I am using magento 1.6.1 version.

I had not set any cookie path or anything from admin or frontend. Please let me know the complete process – How I get the logged in user status outside the magento folder.

I had tried with the web-services. I had used its core functions but again not getting what I want.

In one line – I am trying to get the logged in user details out side the magento installation folder.

Richard I need it running very desperately so please please please help me out.

Thanks for time for writing some code for me that run for the magento version.

Regards,
Vikas

Avatar

Vikas INDIA

January 31st, 2012 at 5:43 pm

Hello Richard,

Had you find something for me. Please let me know if I need to explain more about what I need and what I am doing.

Regards,
Vikas

Avatar

Vikas INDIA

February 20th, 2012 at 1:04 pm

Hello Richard,

Can you please help me in this. I am totally lost in this. Pleeeease help.

Process :

I wish to access the magento current session cookie out side the magento folder.

Regards,
Vikas

Avatar

Swaraaj INDIA

October 15th, 2012 at 10:20 pm

Hi Richard,
I am facing the same problem as Vikas mentioned, i used the code you have mentioned in your earlier post…i.e. http://mysillypointofview.richardferaro.com/2009/04/13/how-to-run-magento-session-to-an-external-site/ but in the version 1.7.0.2 and whenever i am trying to access the session outside the magento folder. i am always getting not logged in response. not able to find out whats the problem is? please help. Thanks in advance.

Avatar

Richard Feraro

October 15th, 2012 at 11:17 pm

Hi :)
Have you check the cookie path? Make sure that your script is within the Magento’s cookie path for it to work.

Avatar

Swaraaj INDIA

October 15th, 2012 at 11:31 pm

Hi Richard.

Thanks for your quick response, on my localhost magento is installed in www/magento and cookie path which is generated after customer login(for frontend) is /magento while, script for testing is located at www folder and cookie its generating for frontend at path / only.

I want to know that to use magento session is it necessary to put the testing script file into the magento intstallation?

Avatar

Richard Feraro

October 15th, 2012 at 11:50 pm

Edit your Magento cookie path setting to ‘/’ in the Magento admin. Try again after saving it.

Avatar

Swaraaj INDIA

October 16th, 2012 at 12:06 am

Thanks a lot Richard. It worked.
Overall session can be read only when two applications are on the same place only thanks a lot again for your help.
Thanks again. :)

Avatar

mark PHILIPPINES

December 3rd, 2012 at 1:22 pm

Hi Richard,

How could I make sure that my script is within the Magento’s cookie path (steps). I am running it thru localhost and my script just kept on going on the log-in form though I ama already logged-in on the mage admin. I’m so sorry but I am only a beginner in Magento.Thanks.

Avatar

Richard Feraro

December 4th, 2012 at 3:15 am

Post your script here so I can examine it.

Avatar

Djordje Karanovic GERMANY

February 4th, 2013 at 5:25 pm

Hi Richard,

Nice post it really helps!

I am using Magento 1.7.0.2 as a backend and TYPO3 4.7.7 as frontend and your code works if I am at the same time logged in TYPO3 as admin. But if I am not logged in TYPO3 it doesn’t work. Do you have any suggestions?

Regards,
Dj.

Avatar

Richard Feraro AUSTRALIA

February 5th, 2013 at 2:24 pm

Check the domain of the cookie being created. As long as both site are within that domain, the session will work.

Avatar

vinod INDIA

September 5th, 2013 at 6:40 pm

hi

i want to use external session into magento. Please let me know how we can use it. i want to use simple session in header.phtml.

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.

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

Join 11 other subscribers

PayPal Donation

WordPress + Magento

Proudly Pinoy!

Proudly Pinoy!

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.