Do user login with curl and the services 3.x module in Drupal 7
Last updated on
30 April 2025
You are browsing documentation for an older version of Drupal, which is not supported any longer, and the information may not be correct. See current documentation for Contributed modules
Assume that I created an rest server endpoint:
http://localhost:3000/rest_api/user/login and I have an account with username: jimthunderbird and password 123456, here is how to log the user in using curl and the services module in Drupal 7
// Retrieve CSRF token
$curl_get = curl_init();
curl_setopt_array($curl_get, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://localhost:3000/services/session/token',
));
$csrf_token = curl_exec($curl_get);
curl_close($curl_get);
$csrf_header = 'X-CSRF-Token: ' . $csrf_token;
// REST Server URL
$request_url = 'http://localhost:3000/rest_api/user/login';
// User data
$user_data = array(
'username' => 'jimthunderbird',
'password' => '123456',
);
// cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $csrf_header));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
print $response;
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check if login was successful
if ($http_code == 200) {
// Convert json response as array
$logged_user = json_decode($response);
}
else {
// Get error msg
$http_message = curl_error($curl);
die($http_message);
}
print_r($logged_user);
Help improve this page
Page status: Not set
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion