How to create user account programmatically in Magento?

By | June 27, 2014

Unfortunately, there is no any API to create user account in Magento, We can create a customer using Magento Class / API.
which is very useful when we want to register a certain customers that registering in a form that outside of our Magento site.

So, here’s the code to create a user account programmatically in Magento

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);

require_once 'app/Mage.php'; // please include full path of Mage.php

Mage::app('default');

$customer_email = 'test@magentotutorial.in';  // email address 
$customer_fname = 'firstname';      // first name  
$customer_lname = 'lastname';       // last name 
$passwordLength = 10;               // the lenght of autogenerated password
$passowrd       = '123456';         // you can assign password or auto generated password, you have two option

$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($customer_email);
/*
* Check if the email exist on the system.
* If exist, it will not create a user account. 
*/

if(!$customer->getId()) {

   //setting data as email, firstname, lastname, and password 

  $customer->setEmail($customer_email); 
  $customer->setFirstname($customer_fname);
  $customer->setLastname($customer_lname);
  //$customer->setPassword($customer->generatePassword($passwordLength)); // you can use autogenerated password
  //or
  $customer->setPassword($password); //or can set your own password as you wish

}
try{
  //the save the data and send the new account email.
  $customer->save();
  $customer->setConfirmation(null);
  $customer->save(); 
  $customer->sendNewAccountEmail();
}

catch(Exception $ex){
echo $message = $ex->getMessage(); 
}
?>

Hope, you will enjoy!.

Leave a Reply