XF 2.1 What is the best way to update multiple users using the API?

BubbaLovesCheese

Active member
Hi,

I have been using PostMan for my API requests, but I'm happy to try another method if it is easier.
  • I would like to update the secondary_group_ids of about 60 different users.
  • There could be up to 4 different values for the secondary_group_ids, for each user.
This just needs to be run once, when I'm setting up the forum.

I was just wondering what is the easy method to accomplish this?

I could set up a .csv with the value beforehand if that helps.

Thanks.
 
It's been a while, but....
  1. Create a new directory on your server
  2. Download and install httpful.phar in the same directory. (I can't remember how I did that, or where I got the file from, but maybe google or someone else can help)
  3. Copy the following PHP file below and put it in the same directory (so now you have 2 file in that directory, httpful.phar and codebelow.php
  4. Then run the php file. And that should be it.

NOTE: You need to change 3 things in the code:
  • Replace example.com with your url
  • Replace YourAPIKeyGoesHere with your API
  • And replace 3 => [32,30,21,11,16] with <youruserid> => [<yourforumid1,yourforumid2,yourforumid3,etc...>]

PHP:
<?php

include('httpful.phar');

use \Httpful\Mime;

/*
* Insert your own user id and forum id below using the following format:
* userid => [forumid1,forumid2,forumid3,forumid4],
* 3 => [32,30,21,11,16],
*/

$userForums = [
3 => [32,30,21,11,16],
4 => [11],
19 => [21],
53 => [21,34],
85 => [21],
88 => [10,33,27,17,21,15,34],
100 => [17],
111 => [29,22,14,16,28,21],
204 => [31],
225 => [14]];
    
foreach($userForums as $user => $forums) {
    $response = updateUserForum($user, $forums);

    echo $response->body->success ."\n";
}

/*
* Insert your own URL and API below
*/

function updateUserForum($user, array $forums) {
    $url = "https://example.com/api/users/$user/";
    $apiUser = 1;
    $apiKey = 'YourAPIKeyGoesHere';

    $payload = implode('&', array_map(function($forum) {
        return "secondary_group_ids[]=$forum";
    }, $forums));

    return \Httpful\Request::post($url)
        ->addHeaders(['XF-Api-User' => $apiUser, 'XF-Api-Key' => $apiKey])
        ->body($payload)
        ->sendsType(Mime::FORM)
        ->send();
}
 
Top Bottom