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.
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.