hobbitty hobbitty - 1 month ago 14
PHP Question

remove anonymous session cookies php

I am using

session_start();


at the beginning of my PHP scripts. I have recently installed varnish to do some caching, so I would like for PHPSESSID to disappear when a user is anonymous (or not logged in).

I thought to set a custom header in my PHP script (which goes in the response header) if the user was not logged in, and cache such pages. But I don't think this will work since the Cookie is in the request header, which if I am understanding correctly, is why varnish is not caching.

How can I resolve this scenario? Deleting the request cookie for anonymous users seems ideal.

Joe Joe
Answer

There are a few factors involved here, so please pardon my lack of brevity in favor of completeness. First of all, session_destroy() only deletes the server-side session data, not the PHPSESSID cookie (or an existing response header request to set a session cookie). If any cookies already exist on the client a setcookie() command would need to be called also to overwrite the PHPSESSID cookie with another that has an expiry date already in the past, that will cause the browser to delete the cookie after the http request processes, although it won't help the fact that the PHPSESSID cookie is still present in the current request, stopping Varnish. If you can chase every session_start() command with a conditional to destroy it and remove the set-cookie header from the response before it ever gets to the client then that could work, but it's a very unstable band-aid. It's also possible to override PHP's session handling so that the entire session_start process goes through a conditional, but that's also a rough patch (more info at: http://php.net/manual/en/class.sessionhandler.php)

Varnish does have some documentation on selectively bypassing certain cookies (primarily used with Google Analytics cookies): https://www.varnish-cache.org/docs/3.0/tutorial/cookies.html The catch is that, from Varnish's perspective, it can't tell a filled PHP session vs an empty one, so even people who are logged in would be served cached pages from Varnish. I'd suggest, having Varnish ignore the PHPSESSID cookie but set an additional cookie on proper login that Varnish isn't set to bypass, so that those requests will be passed through to the backend.