Skip to content

Instantly share code, notes, and snippets.

@toddway
Created March 15, 2013 16:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toddway/5171043 to your computer and use it in GitHub Desktop.
Save toddway/5171043 to your computer and use it in GitHub Desktop.
PHP/Drupal example of making an authenticated user search request to the Passport API
<?php
/*
PHP/Drupal example of making an authenticated user search request to the Passport API
*/
function example_passport_api_request() {
$server = 'http://example.com/rest/';
//login request - we need to authenticate before requesting protected data
$username = 'username';
$password = 'password';
$url = $server . 'user/login.json';
$options = array(
'method' => 'POST',
'headers' => array('Content-Type' => 'application/json'),
'data' => json_encode(array(
'username' => $username,
'password' => $password,
)),
);
$result = drupal_http_request($url, $options['headers'], $options['method'], $options['data']); //d6 //$result = drupal_http_request($url, $options); //d7
if ($result->code != 200) {
drupal_set_message(t('Authentication error: ') . $result->status_message, 'error');
}
$login_data = json_decode($result->data);
$cookie = $login_data->session_name . "=" . $login_data->sessid . ";"; //build the session cookie from our login repsonse so we can pass it on subsequent requests
//user search request
$url = $server . 'search/user_index/ui.json?keys=joe&sort=field_anniversary:DESC'; //$url = $server . 'search/user_index/ui.json';
$options = array(
'method' => 'GET',
'headers' => array(
'Content-Type' => 'application/json',
'Cookie' => $cookie, //add our auth cookie to the header
),
);
$result = drupal_http_request($url, $options['headers'], $options['method'], $options['data']); //d6 //$result = drupal_http_request($url, $options); //d7
dpm(json_decode($result->data), 'result data');
//Log out request, since we are done now.
$url = $server . 'user/logout.json';
$options = array(
'method' => 'POST',
'headers' => array('Cookie' => $cookie),
);
$result = drupal_http_request($url, $options['headers'], $options['method'], $options['data']); //d6 //$result = drupal_http_request($url, $options); //d7
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment