Stephen Adelakun
Stephen Adelakun

Reputation: 804

What are the implications of sending cookies over secure connections in PHP

I recently began to look very closely at PHP sessions with a bid to strengthening my websites' security. I came across session_set_cookie_params(). I was particularly interested in the 4th parameter( boolean secure ). Does it mean the site must operate secure http ( https ) protocol in order to set this parameter to true? If not, how does PHP then send cookies over a secure connection for a site that only uses http protocol?

Upvotes: 1

Views: 198

Answers (2)

deceze
deceze

Reputation: 522042

The secure flag is part of the specification for cookies. If a browser receives a cookie with the secure flag set, it will not send this cookie back to the server unless the connection is HTTPS encrypted. PHP will set the cookie regardless of the current connection status, it doesn't ultimately know or care about the presence of HTTPS; it's up to you to ensure that you're also setting the cookie over HTTPS.

You should send authentication cookies exclusively over HTTPS to avoid outright session hijacking by men-in-the-middle or other unsecured networks (e.g. shared unencrypted Starbucks Wifi). Otherwise snatching the secret session identifier out of the air is a real possibility and therefore anyone can impersonate anyone. And that means the entire time a user is logged in, it should communicate with your server over HTTPS, since the cookie is going back and forth the entire time; using HTTPS only for the initial login page is not enough.

Upvotes: 1

Tom
Tom

Reputation: 4826

By default cookies are sent for all requests (http and https).

If you set the secure flag to true, the browser will only send them for https requests.

It's important to always set the secure flag for authentication cookies : even if you don't make http requests, someone else can force the browser to do it, and even if you answer 301, it's already too late, they're already sent in clear text.

For a full https website, you can systematically set the secure flag to true.

Upvotes: 0

Related Questions