Create a gist now

Instantly share code, notes, and snippets.

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