Skip to content

Fig Cookies - Modifying cookie value (JSON array) #13

@JamesTheHacker

Description

@JamesTheHacker

I want to be able to store an array of ID's to their cookies. I figured the easiest way is to json_encode the array of save IDs. Code below:

$app->get('/save/{id: [0-9]+}', function($request, $response, $args) {

  // Check if cookie exists
  $cookie = FigRequestCookies::get($request, 'saves');

  if($cookie->getValue() !== "null") {

    // Convert old cookie JSON array to PHP array
    $saves = json_decode($cookie->getValue(), true);

    // Push new save ID onto array
    array_push($saves, $args['id']);

    // Modify cookie
    $response = FigResponseCookies::modify($response, 'saves', function(SetCookie $setCookie) use ($saves)  {
      return $setCookie->withValue(json_encode($saves));
    });
  }
  else {

    // No cookie found set one
    $setCookie = SetCookie::create('saves')
      ->withValue(json_encode([ $args['id'] ]))
      ->rememberForever()
      ->withPath('/')
      ->withDomain('.localhost');

    $response = FigResponseCookies::set($response, $setCookie);
  }

  // Return user to save area
  return $this->view->render($response, 'saves.php');
});

My problem is the array only ever gets two values regardless of how many times I save a page. If I visit the following pages ...

http://example.com/save/22
http://example.com/save/32
http://example.com/save/18

... the array of $saves is only ever set to:

[22, 18]

If I save another page:

http://example.com/save/9

... the array is:

[22, 9]

Not sure what's going on here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions