Quantcast
Channel: Eureka! » PHP
Viewing all articles
Browse latest Browse all 16

Drupal 8 – Login in Guzzle Web Service Client @ 1

$
0
0

1. Get your PHP client ready by following my previous post.

 

2. Update your index.php as follow.

<?php
  require 'vendor/autoload.php';
  use Guzzle\Http\Client;
  use Guzzle\Plugin\Cookie\CookiePlugin;
  use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

  $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
  $client = new Client('http://drupal8.localhost.com');
  
  $client->addSubscriber($cookiePlugin); 
  $request = $client->post('user', null, array(
    'name' => '<username>',
    'pass' => '<password>',
    'form_id' => 'user_login_form',
  ));
  $request->addHeader('Accept', 'application/json');

  $response = $request->send()->json();

  print '<pre>';
  print_r($response);
  print '</pre>';
?>

 

3. Try it out!
drupal-8-web-service-login
 

4. If it works, you can now always use the $client object for all future requests. For example, if you only allow authenticated user to access the content, the following piece of code will return you the corresponding node content.

<?php
  require 'vendor/autoload.php';
  use Guzzle\Http\Client;
  use Guzzle\Plugin\Cookie\CookiePlugin;
  use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

  $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
  $client = new Client('http://drupal8.localhost.com');
  
  $client->addSubscriber($cookiePlugin); 
  $client->post('user', null, array(
    'name' => '<username>',
    'pass' => '<password>',
    'form_id' => 'user_login_form',
  ))->send();

  $request = $client->get('entity/node/1');
  $request->addHeader('Accept', 'application/json');
  $response = $request->send()->json();

  print '<pre>';
  print_r($response);
  print '</pre>';
?>

 

5. An exception will be thrown without login or the login credential is incorrect.
drupal-8-web-service-login-access-denied
 

Done =)

Reference: Drupal Community – REST: exposing data as RESTful web services


Filed under: CMS, PHP Tagged: Drupal, Drupal 8, Drupal Development, Guzzle, PHP, RESTful, Web Service

Viewing all articles
Browse latest Browse all 16

Trending Articles