Magento – Get customer login form key

form-keymagento-1.9

I want create login functionality outside magento, but same server.
For this I created a login form, but without correct form key it is useless.

Is there way to get customer login form key?

Here is my code. But it gives different key

<?php
require 'store/app/Mage.php';
Mage::app(); 
// Define the path to the root of Magento installation.
define('ROOT', Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB));

// Obtain the general session and search for an item called 'customer_id'
$coreSession = Mage::getSingleton('core/session', array('name' => 'frontend'));

$key = Mage::getSingleton('core/session')->getFormKey(); 
?>

<form action="mydomain/store/customer/account/loginPost/" method="post">
    <input name="form_key" value="<?php echo $key; ?>" type="hidden">
    <input type="text" name="login[username]" value="username" />
    <input type="password" name="login[password]" value="password" />
    <input type="submit" name="submit" value="submit" />
</form>

Edit

My Problem is $this->getBlockHtml('formkey'); and Mage::getSingleton('core/session')->getFormKey() not same is there any way to use real form key.

Best Answer

You need to some change at your code;

Call a frontend design by Mage::app()->loadArea('frontend');

then Call formkey block from current exiting layout $layout = Mage::getSingleton('core/layout');

get block by code:

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

//load default xml layout handle and generate blocks
$layout->getUpdate()->load('default');  // add default handler
$layout->generateXml()->generateBlocks();

//get the loaded head and header blocks and output
$BlockHtml = $layout->getBlock('BlockName');

 echo $BlockHtml->toHtml() 

For this case you will get same session form_key value:

Modified code:

<?php
require '../app/Mage.php';
umask(0);
Mage::app()->loadArea('frontend');
define('ROOT', Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB));

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

//load default xml layout handle and generate blocks
$layout->getUpdate()->load('default');
$layout->generateXml()->generateBlocks();

//get the loaded head and header blocks and output
$formkeyBlock = $layout->getBlock('formkey');
$key= Mage::getSingleton('core/session')->getFormKey(); 
?>
  <form action="mydomain/store/customer/account/loginPost/" method="post">
    <input name="form_key" value="<?php echo $key; ?>" type="hidden">
    <input type="text" name="login[username]" value="username" />
<?php echo $formkeyBlock->toHtml()  ?>
    <input type="password" name="login[password]" value="password" />

    <input type="submit" name="submit" value="submit" />

    </form>