I would argue that the original post of an error is flawed. The suggestion being made is that because the session cookie is not “secured” there is an alternative and therefore it needs to be fixed. This assumption needs to be tested.
First, consider that cookies are returned only to the domain that issued them. Next consider that it is possible that someone has modified a template to pull JavaScript code from another site. Is possible that this JavaScript could read a cookie destined for its own domain? I would agree that it is possible. This would then appear to be a security issue.
But we need to look deeper and consider what options are available to address this issue at this time. First, if the domain is access in http mode, the “secure” flag offers no assistance since it will not send the cookie across and unsecure channel. Since most sites are referenced initially in http mode, all the session cookies are potentially exposed. Using the above posted code, it sets the session cookie to “secure” when the site moves to https mode. This would appear to be a good thing, except the session has already been exposed. But consider what happens when the site moved from https back to http mode, the session cookie is not presented since it is an unsecure channel. PHP is forced to create a new session resulting in the lost of all session data.
Can this be gotten around? Sure, by placing the session id in the URL or as part of the fields on the page to be posted back, the code can detect and adjust the session name. But this is the worst security practice. The browser will enforce returning a cookie to its own domain. The web page code can be read or posted to whatever site. Worst, the URL with the session embedded in it can be copy and pasted wherever.
For the best security, the session ID should appear ONLY in the session cookie and never anywhere else.
So what we end up with is something that does not work and the only way to make it work is to expose the session even more.
There is an actual proposed solution that solves this issue, but is not currently part of the official W3C standards. Microsoft, of all people, has proposed the HTTPOnly flag which will prevent the session cookie from being access by JavaScript. But until it is accepted as a standard, it will have questionable support in the browsers.