POST example with Guzzle and session cookies

Public

Warning message

We recommend you to assign at least one category to this snippet so you could easily navigate it in the future. Edit your snippet here.

POST example with Guzzle and session cookies
Using session authentication for a POST request is a bit more complicated than HTTP Basic Authentication, because we need to provide a CSRF protection token. This is necessary to protect web browser users from malicious sites that could trigger RESTful POST requests on the user's behalf.

Example of POSTing a node with Guzzle version 4:

Get raw version
php
  1. <?php
  2. require_once($_SERVER['DOCUMENT_ROOT'] . '/core/vendor/autoload.php');
  3.  
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Exception\RequestException;
  6.  
  7. $base_url = 'http://example.com';
  8.  
  9. try {
  10.  
  11. $client = new Client([
  12. 'base_url' => $base_url,
  13. 'cookies' => true,
  14. 'allow_redirects' => true,
  15. 'debug' => true
  16. ]);
  17.  
  18. $response = $client->post("/user/login", [
  19. 'cookies' => true,
  20. "body" => [
  21. "name"=> "username",
  22. "pass"=> "password",
  23. 'form_id' => 'user_login_form'
  24. ]
  25. ]);
  26.  
  27. $token = $client->get('rest/session/token', [
  28. 'cookies' => true
  29. ])->getBody(TRUE);
  30.  
  31. $token = (string)$token;
  32.  
  33. $node = array(
  34. '_links' => array(
  35. 'type' => array(
  36. 'href' => $base_url . '/rest/type/node/page'
  37. )
  38. ),
  39. 'title' => array(0 => array('value' => 'New node title')),
  40. );
  41.  
  42. $response = $client->post('entity/node', [
  43. 'cookies' => true,
  44. 'headers' => [
  45. 'Accept' => 'application/json',
  46. 'Content-type' => 'application/hal+json',
  47. 'X-CSRF-Token' => $token,
  48. ],
  49. 'json' => $node
  50. ]);
  51. if ($response->getStatusCode() == 201) {
  52. print 'Node creation successful!';
  53. } else {
  54. print "unsuccessful... keep trying";
  55. print_r(get_defined_vars());
  56. }
  57. } catch(RequestException $e) {
  58. echo $e->getRequest();
  59. echo "\n\n";
  60. if ($e->hasResponse()) {
  61. echo $e->getResponse();
  62. }
  63. }
  64. ?>