Back to Top

How to Import Users in MODx from CSV file

Before few days, I have explained To send mail in modx and Execute Custom Query IN MODx and Today I am going to explain how to import users by external CSV file in MODx Revolution.

Well, I am going to explain to import user from an external script rather than using snippet or any resource in MODx Revolution.
First off, Let’s check how to load MODx object in external PHP file instead of as a snippet on an MODx resource, following line of code is useful.

require_once '/absolute_path/config.core.php';
require_once MODX_CORE_PATH.'model/modx.class.php';
$modx = new modX();
$modx- >initialize('web');
$modx- >getService('error','error.modError');

Above code will initialize the MODx object into the web. Now, if you want to access it under a different context, you’ll just need to change the web to whatever Context you want to load into the initialize. This also loads the MODX error handler as well.

//To get Base Path
$basePath = $modx- >config['base_path'];
// Prepare the data
if (file_exists($basePath."users.csv")){
	$fp = fopen($basePath."users.csv","r");
	$ausers =array();
	while($data=fgetcsv($fp,900000,",")){
		$datas =array(
			'email' = > $data[0],
			'password' = > $data[1],
			// Will be encrypted automatically in the below process
		);
	array_push($ausers,$datas);
	}
}

Above Code is used to get data from the CSV file and here I have pushed the data into the array $ausers.

Now, Lets set array data by using the following line of codes:

foreach ($ausers as $fields) {
	$email=$fields['email'];
	$passwd=$fields['password'];
	// Query to check Email address is unique,not exists in database.
	$stmt = $modx- >query("select email from mx_users where email = $email");
	$result = $stmt- >fetchAll(PDO::FETCH_COLUMN);
	if(count($result)==0 )
		{
             /* To create user and profile */
            $user = $modx- >newObject('modUser');
            $profile = $modx- >newObject('modUserProfile');
            /* To override class key */
            if (empty($fields['class_key'])) $fields['class_key'] = 'modUser';
            /* set user and profile */
            $user- >fromArray($fields);
            $user- >set('username',email);
            $user- >set('active',1); // 1 to set user as active,0 for inactive
            $version = $modx- >getVersionData();
            $user- >set('password',$passwd);
            $profile- >fromArray($fields);
            $profile- >set('internalKey',0);
            $user- >addOne($profile,'Profile');
            /* To save user */
            if (!$user- >save()) {
            $modx- >log(modX::LOG_LEVEL_ERROR,'Could not save registered user:
            '.$user- >get('id').' with username:
            '.$user- >get('username'));
            return 'Error saving user '.print_r($scriptProperties,true);
        }else{
                $userId =$user- >get('id');
                // To get saved user id
                $user = (!empty($userId)) ? $modx- >getObject('modUser', $userId)
                : $modx- >user;
                /* To store extended data */
                $extendedFields = array();
                $extendedFields = $profile- >get('extended');
                $extendedFields['gender'] = $fields['gender'];
                $profile- >set('extended', $extendedFields);
                $profile- >save();
                /* To send mail to users */
                $scriptProperties =array();
                $modx- >getService('mail', 'mail.modPHPMailer');
                $modx- >mail- >set(modMail::MAIL_BODY, $body);
                $modx- >mail- >set(modMail::MAIL_FROM, '[email protected]');
                $modx- >mail- >set(modMail::MAIL_FROM_NAME, 'admin');
                $modx- >mail- >set(modMail::MAIL_SENDER, $email);
                $modx- >mail- >set(modMail::MAIL_SUBJECT, 'Your Account has been created');
                $modx- >mail- >address('to', $email, $user- >get('username'));
                $modx- >mail- >setHTML(true);
                $sent = $modx- >mail- >send();
		}
	}else{
		continue;// If user already exists
    }
}

Let me explain above code here.First off, I have checked that user email address is unique by applying query.Then after I have created user and profile then set the user and profile value. Next save the user. After that, I have to get the last inserted user id and update the extended field of a user by using the set extended and send information mail to user.

Some more articles:

Accordion Menu with Modx
Move Modx Revolution to Live Server
To Reset resourceID in MODx

That’s it.I hope this script will helpful to externally import the user in Modx Revolution.I hope this post will help you. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

Comments (2)

  1. I keep getting an error that I can’t figure out with this:

    PHP Fatal error: Call to a member function fetchAll() on a non-object

    This is in reference to this line:
    $result = $stmt->fetchAll(PDO::FETCH_COLUMN);

    Any ideas? Thanks!

    1. Are you doing same mentioned in article?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to use HTML5 AutoFocus attribute

Posted on 4 years ago

Bhumi

How to perform Operations in LESS CSS?

Posted on 4 years ago

Bhumi

Overview of ECMAScript 6 new Features

Posted on 1 year ago

Bhumi

The Readers’ Poll – June 2013

Posted on 6 years ago

Bhumi

Hello world

Updated 5 days ago

Nick Carter

In depth Understanding of Laravel Core

Updated 2 months ago

Bhumi

ECMAScript 6 New Features – 2

Updated 1 year ago

Bhumi

The Reader’s Poll – June 2015

Posted on 4 years ago

Bhumi

The Reader’s Poll – August 2014

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 5 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 5 years ago

Bhumi

The Readers’ Poll – August 2013

Posted on 5 years ago

Bhumi