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 Magento Enterprise Certified developer from Manila, Philippines with 14 years of solid open-source development experience using Linux, Apache, MySQL & PHP.

By Richard Feraro

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

Leave a Reply