Login to Magento via Curl (Cross Domain)
If you have ever wanted to be able to login your customers from an external domain you can do so in two obvious ways:
1. Use an HTML form to post to the login controller in Magento
<form action="http://www.mymagentosite.co.uk/customer/account/loginPost" method="post"> <input type="text" name="login[username]" value="username" /> <input type="password" name="login[password]" value="password" /> <input type="submit" name="submit" value="submit" /> </form>
However if you want to be able to log the customer in without them filling out a form then perhaps the following method is good for you?
2. Using Curl
Firstly we need to have the correct username+password for our customer – as long as you have this it shouldn’t be a problem.
On our external domain we can create a new file – something like crossdomainlogin.php.
In this php file paste in the following:
session_start(); $string = "login[username]=".urlencode("email@example.com")."&login[password]=".urlencode("password"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://www.mymagentodomain.co.uk/customer/account/loginPost'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIE, session_name().'='.session_id()); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $string); curl_setopt($ch, CURLOPT_HEADER, true); $output = (string) curl_exec($ch); curl_close($ch); preg_match('/frontend=(.+); expires=/i', $output, $matches); $temp = $matches; $sid = str_replace(array("frontend=","; expires="), "", $temp); //echo $sid; header('Location: http://www.mymagentodomain.co.uk/customer/account/?SID='.$sid);
What the above code does is:
- Log’s you in via Curl
- Stores the new session ID
- Transfers you to the Magento site with the new session ID stamped to your URL
I hope you have enjoyed this blog and find it useful – thanks for visiting the Magento Blog here at e-commerce web design, home of the Magento Fox!