Skip to content

Instantly share code, notes, and snippets.

@luukverhoeven
Last active July 28, 2020 15:54
Show Gist options
  • Save luukverhoeven/255105bc9b82b2633b5a89767d1abc3c to your computer and use it in GitHub Desktop.
Save luukverhoeven/255105bc9b82b2633b5a89767d1abc3c to your computer and use it in GitHub Desktop.
Moodle webservice client sample
<?php
/**
* Send a Post request
*
* @param string $moodleFunction
* @param array $data
*
* @return array
*/
function sendPostRequest($moodleFunction = '', $data = []) {
$defaultMoodleUrl = 'https://moodle.domein.nl/webservice/rest/server.php';
$moodleToken = 'e3e7dcf14c5aa958c412642c1b339fc1';
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => sprintf("%s?wstoken=%s&wsfunction=%s&moodlewsrestformat=json", $defaultMoodleUrl, $moodleToken, $moodleFunction),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
if ($status !== 200) {
throw new Exception('Curl invalid response code : ' . $status);
}
if (!empty($error)) {
throw new Exception("Curl error message: " . $error);
}
// If there's an error we stop and throw a error, all request should be correct.
$response = json_decode($response, true);
// For debugging purpose we show all responses.
// echo '<pre>DEBUGGING:';
// print_r($data);
// print_r($response);
// echo '</pre>';
return $response;
}
$userData = [
'users[0][username]' => 'piet1', //Username policy is defined in Moodle security config.
'users[0][password]' => 'Piet1234!', //Plain text password consisting of any characters
'users[0][firstname]' => 'Piet', //The first name(s) of the user
'users[0][lastname]' => 'Test', //The family name of the user
'users[0][email]' => '[email protected]', //A valid and unique email address
'users[0][idnumber]' => '', //An arbitrary ID code number perhaps from the institution
// Optional profile fields.
//'users[0][customfields][0][type]' => 'iban',
//'users[0][customfields][0][value]' => '51252151325',
];
try{
// Create.
$response = sendPostRequest("core_user_create_users", $userData);
// Update.
$response = sendPostRequest("core_user_update_users", $userData);
// Get user.
$response = sendPostRequest("core_user_get_users", [
'criteria[0][key]' => 'email', // Search
'criteria[0][value]' => '[email protected]', // Value
]);
// Get user.
$response = sendPostRequest("core_user_delete_users", [
'userids[0]' => 3000, //user ID
]);
var_dump($response);
}catch(Exception $exception){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
@luukverhoeven
Copy link
Author

luukverhoeven commented Jul 28, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment