Skip to content

Instantly share code, notes, and snippets.

@kreativmonkey
Last active April 8, 2017 09:50
Show Gist options
  • Save kreativmonkey/3bc8d2d8a13fbbc9f7076ca03a6ce41d to your computer and use it in GitHub Desktop.
Save kreativmonkey/3bc8d2d8a13fbbc9f7076ca03a6ce41d to your computer and use it in GitHub Desktop.
Processwire Userimport
<?php
/*********************************************
* Import Users by JSON file
*
*********************************************/
function import($file){
$string = file_get_contents($file); // Read JSON file
$users = json_decode($string, true); // Decode JSON to $users array
// Iterate to each user
foreach ($users as $user) {
$sanitizer = wire('sanitizer'); // initialize $sanitizer for input sanitizing
/*****************************************************
* Make shure there is no user with the same username
* you can skip, update or add the user
*****************************************************/
$counter = '';
if(wire('users')->get("name={$user['Name']}")){
// Skip double users by uncommand the following line
// continue;
// Add the User by adding a number to his name
$counter = wire('users')->count("firstname={$user['Name']}") + 1; // count all users with the same name.
// Update the user.
// $u = wire('users')->get("name={$user['Name']});
}
if(empty($u)) $u = new User(); // Create new User
$u->of(false); // Outputformatting of for adding new values to the user
/***************************************************
* Now you can add the Information from the JSON file
* to the new User. Don't forgett to sanitize the inputs.
****************************************************/
$u->name = $sanitizer->name($user['Name']). $counter; // name as username + counter if more user has the same name.
$u->email = $sanitizer->email($user['email']);
$u->pass = $sanitizer->text($user['password']);
$u->addRole('User'); // Add Userrole to the User
// Save the User
$u->save();
$u->of(true);
// Feedback for each added user.
echo "User: {$u->name} added. <br />";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment