Recommended way to set, get, remove cookies?

Hi there!
Believe it or not, but I’m upgrading from Slim 2. (Still in the process of upgrading an app to v3… Hoping to get to v4 tomorrow.)

Cookies have been a pain point:

  • Slim 2 documented how to do it, and it was very straightforward; nice!
  • Slim 3 said to use dflydev/dflydev-fig-cookies, but I’ve wasted 2-3 hours on it today, and it’s bad. The documentation is terrible and, even though the project looks active, their remove method has been broken for over 3 years now.
  • Slim 4 doesn’t mention anything on the topic.

Is there an official recommended way to do it, from the Slim dev team?
If not… does anyone know how people typically do it? Should I just rely on PHP’s built-in functions? (Still gotta read PSR-7.)

Thanks for the help, it’s appreciated.

Hi @fabswt

Is there an official recommended way to do it, from the Slim dev team?

I don’t know.

If not… does anyone know how people typically do it? Should I just rely on PHP’s built-in functions?

I would recommend to use a OOP abstraction for the built-in functions in combination with a Session middleware. Here is a fine collection of session libraries for Slim 4:

1 Like

Aren’t these only for session cookies? Need something to handle cookies that persist after the user closes the browser.

Sessions work with cookies.

Need something to handle cookies that persist after the user closes the browser.

Cookies will be deleted when the browser is closed, unless they have a specific life-time. It’s possible to keep session even after the browser is closed. Use session_set_cookie_parameters() to give the session cookie a non-zero lifetime before starting the session, or set session.cookie_lifetime() to non-zero.

How to setup the cookie lifetime depends on the specific library and some options like gc_maxlifetime and cookie_lifetime:

I use the following for cookie handling: https://github.com/dflydev/dflydev-fig-cookies

I mentioned it in the original post.

My fault, sorry.
I would suggest to override with a expired cookie, which gets deleted by the browser itself, if there is no better solution.