I would like to know if there is a way to prevent PHP from sending a cookie when calling session_start().
My use case is for a site optimisation:
- (1a) I first open a session/send headers.
- (1b) Then generate and output some text content.
- (1c) To enhance session read/write I call “session_write_close” as soon as I don’t need to write in the session anymore.
- (2) Finally I have a post-page rendering process (for stats) that requires a write access to the session. The session is closed, I cannot call session_start() again since it sends a cookie and it’s to late for that. This is a computation-heavy process, so I have to do it after the page is sent to the client.
The client already received a session-cookie. So I don’t need session_start() to send a new (and redundant) one.
Does someone know a way to intercept the cookie or something similar ? Of course I want to avoid the “Cannot send session cookie – headers already sent”. This error is invisible for the user because the page is already renderered but it looks ugly in the logs.
My question seems to be a redundant one, but it is not. I know how headers and content work (send headers first, content after). It’s just that PHP does not let me do what I want.
Yes there is, by telling PHP to not use cookies for sessions. The PHP setting is
session.use_cookies:By default cookies are enabled because they are considered more safe then using URL parameters (see Sessions and securityDocs).
It’s probably possible to tell PHP that the cookie is already set by adding it into the
$_COOKIEsuperglobal arrayDocs. I never experimented with it, but in case you usesession_start()and PHP sees that the session cookie has been already set (by the browser, not PHP,$_COOKIErepresent the browser cookies), it won’t send the headers (again) to set the cookie (which as I understand you is what you want).Edit: Some test script to play around with:
You need to call it with a web-browser (and PHP sessions must be configured to work).