Checking for Magento login on external page - session

I'm hitting a wall here while trying to access items from Magento on an external page (same server, same domain, etc, etc). I want to see if the user is logged into Magento before showing them certain parts on the site.
Keep in mind that this code exists outside of Magento.
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));
if (empty($session))
{
$session = Mage::getSingleton("customer/session");
}
if($session->isLoggedIn())
echo "hi";
$cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
echo $cart;
$cart returns 0, where I definitely have products in my cart. isLoggedIn() also returns false. What am I doing wrong here? Is there an option in Magento that I need to turn on or off to be able to access this information outside of Magento?

Using the code above, I created a php file in the Magento folder. From there, added the number of items in the cart and whether you were logged in or not to an array and encoded it as json. I used some jquery on my external page to grab the file and pull the data I needed.
Not quite the ideal situation, but it works for now.

Are you including Mage.php (which defines getSingleton)?
require_once ($_SERVER['DOCUMENT_ROOT'] . '/app/Mage.php');
What does $session have in it after the getSingleton() call?
print_r ($session);
EDIT: I tried this on my end and was not able to get accurate isLoggedIn() or getItemsCount() data. When I dumped out $session its showing all the fields as 'protected.'
I'm not interested in requiring the user to log in...I merely want to access data from the already logged in session.
Anyone else have any thoughts on this? All the examples out there seem to be pre 1.4.x.

require_once "app/Mage.php";
umask(0);
Mage::app();
// require_once $_SERVER['DOCUMENT_ROOT'] . "/mage1/app/Mage.php";
// Customer Information
$firstname = "krishana";
$lastname = "singh";
$email = "krish.bhati#gmail.com";
$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);
$mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
$mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';
$app = Mage::app ( $mageRunCode, $mageRunType );
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session');
$session->start();
$customer->loadByEmail($email);
$customer_id= $customer->getId();
if($customer_id){
Mage_Core_Model_Session_Abstract_Varien::start();
$session->login($email, $password);
$session->setCustomerAsLoggedIn($session->getCustomer());
echo $session->isLoggedIn() ? $session->getCustomer()->getName().' is online!' : 'not logged in';
}

Related

How to retain Magento customer session throughout all pages?

I am creating customer login using custom php code. I am using API calls for creating the frontend, so I need to maintain the logged in session values throughtout all the pages once the customer has logged in.
Code in a.php
require_once "../magento/app/Mage.php";
Mage::app('default');
umask(0);
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session', array('name' => 'frontend'));
$session->start();
if (!empty($email) && !empty($password )) {
try {
$a = $session->login($email, $password );
$session->setCustomerAsLoggedIn( $session->getCustomer() );
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
}
}
I am able to log in using this code but I need to maintain this logged in session throughout all the pages.
I tried to get the logged in user information from other page. But I can't.
Code in b.php
require_once "../magento/app/Mage.php";
umask(0);
Mage::app('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session');
$session->start();
var_dump(Mage::getSingleton('customer/session')->isLoggedIn());
if($session->isLoggedIn()) {
echo 'User logged In';
} else {
echo 'User not logged In';
}
After calling the page a.php and when I call b.php in the same browser, I need the customer information of the user logged in using a.php? Is that possible? Can anyone help me in this?
Try this one
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
echo $customerData->getId();
}
<?php
require_once "../magento/app/Mage.php";
Mage::app('default');
umask(0);
Mage::getSingleton('core/session', array('name' => 'frontend'));
var_dump(Mage::getSingleton('customer/session')->isLoggedIn());
// print true
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
echo $customerData->getId();
// return customer's id
}

Bring cart count value from Magento cart to ExpressionEngine

I have a website structured as:
www.myEEsite.com/myMAGENTOstore
Where myEEsite is the root of the site and myMAGENTOstore is the Magento site. I'd like them to both look the same site, but I was wondering if there was a way to bring over the cart count value from Magento and display it in the header template of my ExpressionEngine site.
Take a look # Magento cart / session data outside magento
umask(0);
require_once 'app/Mage.php';
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$ItemsCount = Mage::getSingleton('checkout/cart')->getItemsCount();
var_dump(array(
"ItemsCount" =>
$ItemsCount
));
Thanks for the help. Although that didn't work, I was able to successfully achieve with the following code...just changed the path of Mage.php according to my setup:
require_once 'app/Mage.php';
umask(0);
$app = Mage::app('default');
$app->getTranslator()->init('frontend');
if( ($_COOKIE["frontend"]=="") || ($_COOKIE["frontend"]=="undefined") || ($_COOKIE["frontend"]==null) )
{
$session = Mage::getSingleton('customer/session');
session_name('frontend');}
else
{session_name('frontend');}
Mage::getSingleton('core/session', array('name' => 'frontend'));
$className = Mage::getConfig()->getBlockClassName('checkout/cart/sidebar');
$block = new $className();
$block->setTemplate('checkout/cart/sidebar.phtml');
$cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
$carturl = Mage::helper('checkout/url')->getCartUrl();
echo $block->renderView();
echo '<br />cart items count: ' . $cart."<br />";
echo "cart Summary Qty: ".Mage::helper('checkout/cart')->getCart()->getSummaryQty()."<br />";
$cart_count = Mage::helper('checkout/cart')->getCart()->getSummaryQty();

STRANGE...Not able to get cart items in magento on a custom page (only when the customer is logged in)

Here is the standard code I am using for getting cart items and their attributes which works only when the customer is not logged in. As soon as I log in using my account this script stops working and does not return the items in the cart. Also the cart items count is also 0. But as soon as I close the browser(session ends..) and the script returns the cartitems correctly! Very strange, I have not been able to find out the cause. Please guide, anyone?
require_once('../app/Mage.php') ;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName(); //HERE IS THE COMPLETE CODE:<?php
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
//Getting buyer's country label
$bcountry1 = $_REQUEST['country']; //gets country code
$_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
foreach($_countries as $_country){
if ($_country['value']==$bcountry1){$bcountry = $_country['label'];}
}
//Fetching vendor for each product
$config = Mage::getConfig()->getResourceConnectionConfig("default_setup");
$dbinfo = array("host" => $config->host,
"user" => $config->username,
"pass" => $config->password,
"dbname" => $config->dbname );
$hostname = $dbinfo["host"];
$user2 = $dbinfo["user"];
$password = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];
$dbhandle = mysql_connect($hostname,$user2,$password) or die("Unable to connect");
$selected = mysql_select_db("myart2",$dbhandle);
$Proceed=0;
//Getting all products in the cart
//echo $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
$productname = $item->getName();
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $item->getSku(), array('manufacturer'));
$manufacturer = $product->getResource()->getAttribute('manufacturer')->getFrontEnd()->getValue($product);
$qry="select * from vendors WHERE company_name='$manufacturer'";
$result = mysql_query($qry) or die("Unable to run select query");
$row = mysql_fetch_array($result) or die("Unable to fetch data");
if( strcasecmp($row['country'],$bcountry)!=0 && $row['ships_abroad']!=1)
{$Proceed=1;$productnames[]=$productname;}
}
if($Proceed==1)
{
echo implode(',',$productnames);
}
else {echo 1; }
?>
I've tested the following four main permutations, and the code works in a stock CE1.7 instance in all cases:
Create guest quote
Convert guest quote to customer quote via login
Instantiate existing customer quote via login
Merge guest quote with customer quote via login
Adjust the server & app environment params as follows to view & rule out any errors (edit - added complete script; note the closing "}"):
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName();
}

Magento external Script and Session

I want to add an external script which gets a sku via GET check the ID and then redirect to the cart if available otherwise it sets en error and also redirecting to the cart.
The script is called from a product page:
http://myhost/scripts/addto.php?sku=12345
Here is the colmplete code
<?php
include_once '../../../../../app/Mage.php';
Mage::app();
$session = Mage::getSingleton('core/session', array('name' => 'frontend'));
$sku = $_GET['sku'];
if (!isset($_GET['qty'])) { $qty = '1'; } else { $qty = $_GET['qty']; }
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
if ($id == '') {
$id = $sku;
Mage::getSingleton('checkout/session')->addError("Product not found!");
}
Works fine, but after logout and relogin the error message is missing. I found out that's because of a cookie which is set. After deleting that cookie the error message is working again after relogin.
What does not work?
You logout and login and then the script stop working? So the session is not found? The product ist not found? The product is not loaded? The user is not forwarded? :-)
Sure it does not. The Message is a Notice. If it is shown once, it is deleted.
What behaviour do you want?
use Mage::getSingleton('core/session')->addError("Product not found!");, maybe checkout/session is user specific...
cheers

Login To Magento version 1.5.0.1 from outside website

I am trying to login to Magento Admin pannel from out side website but unable to find any way out.My Magento version is 1.5.0.1. I tried the code on url : http://mysillypointofview.richardferaro.com/2010/03/25/how-to-run-magento-version-1-4-0-1-session-to-external-site/#comment-4103 but the code mentioned here is for version 1.4.0.1.
may be you need build 2 client both customize app and magento side
1.create php file to verify magento username
2.send request to magento for authenticate
Create file and try it
require_once "app/Mage.php";
umask(0);
Mage::app();
// require_once $_SERVER['DOCUMENT_ROOT'] . "/mage1/app/Mage.php";
// Customer Information
$firstname = "krishana";
$lastname = "singh";
$email = "krish.bhati#gmail.com";
$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);
$mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
$mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';
$app = Mage::app ( $mageRunCode, $mageRunType );
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session');
$session->start();
$customer->loadByEmail($email);
$customer_id= $customer->getId();
if($customer_id){
Mage_Core_Model_Session_Abstract_Varien::start();
$session->login($email, $password);
$session->setCustomerAsLoggedIn($session->getCustomer());
echo $session->isLoggedIn() ? $session->getCustomer()->getName().' is online!' : 'not logged in';
}

Resources