Skip to content

Instantly share code, notes, and snippets.

@neotohin
Created August 11, 2015 11:08
Show Gist options
  • Save neotohin/ff2450745fa5f1cf2743 to your computer and use it in GitHub Desktop.
Save neotohin/ff2450745fa5f1cf2743 to your computer and use it in GitHub Desktop.
Guzzle based drupal7 Service request sample
<?php
require_once '../vendor/autoload.php';
use Guzzle\Http\Client as Guzzle;
use Guzzle\Plugin\Cookie\CookiePlugin;
use Guzzle\Plugin\Cookie\CookieJar\FileCookieJar;
$client = new Guzzle();
$cookiePlugin = new CookiePlugin(new FileCookieJar('./mydrupal7.cookie.txt'));
$client->addSubscriber($cookiePlugin);
// Sending json encrypted request to server
$request = $client->post('http://mydrupal7/myresource/user/login.json',
array('content-type' => 'application/json'),
[ 'username' => 'tohin', 'password' => 'tohin']
);
$responseObj = $request->send();
$response = $responseObj->getBody();
$res = json_decode($response);
$sessid = $res->sessid;
$sessname = $res->session_name;
$token = $res->token;
// Get Token
function get_x_csrf_token(){
global $cookie, $sessid, $sessname, $client;
$request = $client->post('http://mydrupal7/myresource/user/token' );
$request->setHeader( 'Host', 'mydrupal7');
$request->setHeader( $sessname, $sessid);
$resObj = $request->send();
$array = json_decode( $resObj->getBody() );
return $array->token;
}
$csrf = get_x_csrf_token();
//Log out
$request = $client->post('http://mydrupal7/myresource/user/logout');
$request->setHeader('X-CSRF-TOKEN', get_x_csrf_token() );
$resObj = $request->send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment