What are some of the most common and practical ways a PHP session is used?

New programmer here, and while I've got a general idea of what sessions are, I'm not sure how developers use them to their fullest potential, even how or why they're used at all.  Thanks in advance!
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You use them to preserve data.
You would use them when ever you have something that you need on several different pages but there is no real reason to use a form to pass that information from one page to another.
So say you have a site with a log in, you would use a session to keep that log in information around.
HTTP is a stateless protocol. That means that the web server has absolutely no memory of what just happened 1 second ago. As soon as the web server sends the web page, it forgets about everything and just goes back to watching TV and waiting for the next request to come in.

That's where cookies come in. Cookies introduced a way for data to be stored and re-used. The server could send a special command to the browser to create a new cookie value, and the browser would store the values in a little temporary file on the user's own computer. Later, when the browser re-visited the same site, it could ask the web server for the same page and in the same request, it was able to send the contents of the cookie to the web site.

BROWSER: "Hey, web server, remember me? Is PHP at home? This is a box of information it asked me to bring the next time I came over!"
SERVER: "Wha-? Oh, right. Hey, PHP - there's another person asking for you, and they brought a box full of sensitive information with them."
PHP: "Got it - man, that's a lot of sensitive information to be carrying around, but at least I remember you from all this information contained in your box!"

There were a few problems with cookies (and there still are):

1. Persistent Storage Security

Cookies aren't designed for security in how they are stored. A cookie is just a regular text file, so if a hacker got into your computer, he/she could gain sensitive information from your cookies just by looking at those cookies (depending on whatever was stored inside them).

2. Transmission Security

Cookies aren't designed for security in how they are transmitted. Just like the problem with their long-term storage on the hard drive, they are transmitted in clear text (unless using SSL / HTTPS), so even if someone didn't have access to your hard drive but was on your network, they could eavesdrop on your communication and steal your cookies as the browser sends them.

3. Capacity

Cookies aren't designed for lots of storage. The typical cookie can't hold more than 4k of data (if I recall correctly), and doesn't handle it well when you exceed that amount.

4. Value Types

Cookies aren't designed for different kinds of storage. They can hold text, and that's it.Sessions helped solve some of these issues. Instead of telling the browser to store a text value in the cookie, PHP (and other languages that offer sessions) pretended to be a safety-deposit box and stored all that sensitive data (complex objects like arrays, text values, large values over 4k, etc...) in a file that was located on the server. Then, it would give the safety deposit box key (a unique session ID) to the browser, and this session ID could be stored by the browser in a cookie (either a file-based cookie or a memory-based cookie, depending on how long you wanted the session to last).

So now, the browser had no sensitive data in its cookies, just a series of numbers and letters that acted as a "key" to all the data that was stored on the server for that particular user. Now the conversation went something like this:

BROWSER: "Hey, web server, remember me? Is PHP at home? I've brought this tiny key with me."
SERVER: "Hmm? Oh, right. Hey, PHP - there's yet another person asking for you, and they brought some key with them."
PHP: "Hey stranger. Let me take that key from you... okay, let me find your matching safety deposit box - it's in here somewhere. Got it, oh right - I put this paper with your name on it inside the box last time you visited. Hi, Pete!"

So the risk of sensitive data like account #s being stored on risky hardware or transmitted over risky network connections got minimized because the browser only had a key that unlocked the data on the server. The server didn't send that data back to the browser - PHP simply worked with that session data and locked it back up after it finished creating the web page for the visitor.

Sessions aren't foolproof, though.

1. Persistent Storage Security

The contents of a session data file are still typically stored in un-encrypted files on the server, so they are still at risk for being stolen, but a server typically has better security than the average home PC, so it's a more manageable risk.

2. Session ID Vulnerability

If someone stole / copied the key to your car, that person could steal your car. Likewise, a session ID is still sensitive information because it gives the bearer of that key the access to the session. So if you were logged into your bank account and a hacker stole your session ID and recreated a cookie on their system with that same session ID, and then visited your bank account site, then they would be logged into YOUR account, without even knowing the username or password or anything else! So the session ID can be a "magic key" that also needs to be protected. Nowadays, more session IDs are stored in memory-based, HTTP-only cookies that are much MUCH harder to steal, especially when combined with HTTPS / SSL. Also, sites can regenerate the session ID occasionally to help thwart brute-force attacks.In short, sessions are there to give PHP a way to remember values on a per-user basis and give more control over that data's security to PHP.
Ray PaseurCommented:
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

LB1234Author Commented:
Gr8, that was simply amazing.  I thank you for the time and effort involved in writing that up.  I have a GREAT understanding of sessions, thanks to your A+ response!!  Wow!
LB1234Author Commented:
Ray, I read your article too and it was simply fantastic.  Wow, the EE / PHP gods have smiled upon me during this question! :)  

So when I put the session_start at the top of every page, that keeps the connection with the server "alive."  Got it.  So sessions primarily keep someone from having to log back in? if they close their browser?  What other kinds of things do programmers use sessions to keep alive, besides user account stuff, or is that it?  Sorry if these questions are obtuse.  I don't feel like a natural born programmer at all.  This stuff has been pretty difficult for me, and I'm waaaaaaaaaaaay out of my comfort zone with this stuff.  Thanks!
LB1234Author Commented:
Wait a second!  So a session is a superglobal I can put anything in and as long as I start the page with session_start I can access the information???  COOL!!!
Ray PaseurCommented:
... that keeps the connection with the server "alive."  Got it
WRONG! (Smacks hand on table).

Here is what is really happening.

All of this may seem kind of complicated at first, but once you understand client/server and cookies it will become clear.

The HTTP protocol is stateless, meaning that the server connects and disconnects with each request and inherently remembers nothing from one request to the next.  All of the memory is relegated to the client, which must send everything it wants the server to know in every request.  That means, for example, that the client can send the same cookie over and over, and the server can recognize the cookie over and over.  This creates the illusion that a client is "logged in" but it's really a set of repeated interactions using the same cookie data, and the client / server are both totally disconnected at the end of each request (usually when a web page is served).

The session cookie has a lifespan of zero seconds.  This tells the browser to dispose of the cookie when it closes (last instance of window or tab).  So if the client closes the browser, the session cookie is lost, and the appearance of an automatic logout occurs.

The session is a superglobal; $_SESSION is an array.  You can put many things, but not all things in the $_SESSION array and you can expect to find them from request to request (page to page).  You cannot put resources, such as a query results pointer, into the session.  You cannot put an object instance of stdClass or SimpleXML into the session. Objects in the session can be "serialized" by json_encode(), and you can store the JSON strings.  The reason that built-in PHP objects don't work well as session variables is a little complicated, so for now, just plan your applications so they do not require objects in the session.
LB1234Author Commented:
Ok Got it!  No persistent connections.  A bunch of connections being torn down and reconstructed on the fly.

When i go to amazon, put stuff in my shopping cart, browse for new stuff, and then return back to my cart, was it likely sessions that captured the contents of my shopping cart?  Whereas something more persistent like a wish list will be stored in its database?
Ray PaseurCommented:
On Amazon, it's probably a combination of some kind of session handler and a cookie that connects your browser to their data base.  Consider this scenario...

You go to a shopping site and put some things in your cart or wish list.  The site was created by idiots, so they keep the cart and wish in the PHP $_SESSION array.  You shop around for a while, then your wife calls you to come do something with the dog.  You get a beer, watch a little tennis, then go back to finish your shopping.  But it took you more than 24 minutes since your last HTTP request, and your session has timed out.  All the stuff in your cart was lost and you have to start over.

So the manager at the shopping site finds out about this and calls the idiots on the carpet.  "No more lost shopping carts!"  The idiots go back to their cubicles and decide that they should make everybody register so they can keep a data base that contains your cart and wish list.  The next time you go to the site and click "add to cart" you get diverted from shopping so you can fill out a registration form.  You get annoyed and go shop at the mall instead.

While you're at the mall, you notice that most of the stores allow you to come in and browse, without having to show your credit card and drivers license at the front door.  You wonder why the web site can't figure that out...

The manager finds out about this and fires the idiots.  But he does a really smart thing -- he hires a user-experience designer.  The UX designer says, "Why not make it as easy as possible for people to shop?"  He redesigns the shopping experience to make it completely anonymous right up until the last moment when you have to put in your shipping information.  By that time you have already made the decision to buy and the request for personal information does not feel intrusive, so you're willing share your name, phone, credit card data, email address, etc., and complete the purchase.  A completed purchase is called a "conversion" and it's a Good Thing.  A "conversion ratio" is the ratio of the dollar value of items viewed to the dollar value of items actually purchased.  It ranges from 1 (perfect conversion) to 0 (no conversion)

During the UX shopping experience you were completely unknown to the shopping site.  But they had put a long-life cookie on your browser.  The browser returned this cookie on each request, and the cookie data enabled the shopping site to coordinate your requests with its historical data base records of your cart and wish list.  So even though you were personally unknown during the shopping process, the cookie allowed some personalization, suggestions for companion products, a memory of your cart and wish list, etc.

This change from pre-shopping registration to checkout-coincident registration actually happened in real life at Amazon.com.  By their own estimates it improved the "conversion ratio" considerably.  When the new conversion ratio was applied to the old sales data, it appears that the UX designer made Amazon $300,000,000 by just moving the registration from the front of the store to the back of the store.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.