What if you could make changes or store information about what happens during a users visit to a website? You can with PHP sessions.
This tutorial focuses on:
- What is a session?
- Starting a session
- Storing and using session variables
- Destroying a session
What is a session?
A session is the time a user spends at a website encompassing everything they do in that time at the website. PHP allows for what is called a session variable - a variable that is used to store information about, or change settings for a users session. A session variable can hold information about a single user, and is available to all pages within the same domain.
NOTE: Session information is temporary, it will be deleted once the user leaves a website. For permanent storage, databases or cookies can be used.
Starting a session
The way sessions work is by assigning a unique ID for each visitor and storing data based on this ID. This ID is either stored in a cookie or is part of the URL.
Before being able to store information, you have to start a session. This is accomplished with the session_start() function.
The above example will start a new session, allow you to save information, and assign an ID to the user.
NOTE: The session_start() function must be the first thing in your code, even before the <!DOCTYPE> declaration!
Storing and using session variables
You can store and use session variables through the $_SESSION associative array.
In the above example, the 'views' index of the $_SESSION associative array is incremented by 1 every time a webpage is visited.
Destroying a session
Sessions are destroyed through the use of the session_destroy() function. Using session_destroy() will result in the loss of all data stored in the session. Alternatively, you can use the unset() function which will destroy only some of the data in the session, as opposed to the entire session.