PHP Sessions and Cookies Posted on January 10, 2012

PHP Sessions and PHP Cookies both use cookies.  People tend to think that they both work the same way, but they don’t.

 

Let’s start off with PHP Sessions.  Like PHP Cookies, they use a cookie, aka data stored in a file.  PHP Sessions are not meant to live as long as PHP Cookies, they’re usually temporary sessions.  One of the key differences with the Session cookie is that it is NOT technically stored on the client end.  The cookie itself (with the key / value data) is stored on the server end; while the client gets a cookie with a ID# (aka the PHP Session ID).

 

In basic english, the client gets a session number (literally, the cookie is the session ID#) and the server gets the duplicate ID# with the actual key=>value data.

 

This method prevents the client data from being hacked, but it doesn’t necessarily mean that the session itself can’t be hacked / overtaken.  If someone were to figure out your session ID, they could intercept the data.  One way around this is using PHP’s session regenerate code on every request.

 

PHP cookies work similarly.  However, instead of storing anything on the server end, the data is completely stored on the client’s end (with a expire time).  This keeps load / memory off the server end, but it also comes with a few flaws.

 

PHP cookies can be hacked via packet sniffing over WiFi.. or even hacked via public computers (i.e. you leave your login information on a PC at the library).  So obviously, you would hope your clients / users log out of your site when they’re on public PCs (Or you add an option to your site that says something along the lines of – on public computer; that way the cookie expires at the end of a browser session / and-or expires sooner).

 

The other trick to protect your PHP cookie is to keep your site via HTTPS only.  There are methods of HTTPS packet sniffing, but from what I recall your pc / router can detect a MAC change (the id# of the hardware devices aka detecting interference between the com).

 

And to top it off with a great example: Facebook utilizes PHP cookies to store your login information via OAUTH tokens (no php sessions); they highly recommend you use their site via secure connection (HTTPS), where it can be set in your Facebook settings.

 

If you’d like to learn about or use cookies on your site then please feel free to contact MKN Web Solutions!

Leave a Reply