PHP Sessions
PHP sessions are a way to store data across multiple pages for individual users. They're commonly used to maintain user state and data (like login status, shopping carts, or preferences) throughout a browsing session.
Basics of PHP Sessions
1. Starting a Session
To start a session in PHP, you use the session_start()
function. This must be called before any output is sent to the browser:
2. Storing Data in a Session
Once the session is started, you can store values in the $_SESSION
superglobal array:
3. Accessing Session Data
You can access session data on any page after calling session_start()
:
4. Removing Session Data
-
To remove a specific session variable:
-
To remove all session variables:
-
To destroy the session entirely:
How It Works
-
PHP generates a unique session ID for each user.
-
This session ID is typically stored in a cookie (
PHPSESSID
) on the client's browser. -
On each request, PHP uses this ID to access the associated session data stored on the server.
Common Uses
-
Login and authentication systems
-
Shopping carts
-
Flash messages (temporary success or error notifications)