PHP Sessions
What is a PHP Session?
Session variables hold information about one single user, and are available through all pages in one application.
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you close it. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. user logins, shopping carts, etc).
By default, session variables last until the user closes the browser.
Tip: If you need a permanent storage, you may want to store the data in a database.
PHP Session Functions
The most important session functions are:
session_start()- Starts a new session$_SESSION- Stores and access session variablesunset()- Removes a specific session variable (e.g unset($_SESSION["favcolor"]))session_destroy()- Destroys all data associated with the current sessionsession_unset()- Frees all session variables
Start a PHP Session
A session is started with the session_start() function.
Note: The session_start() function must be
callled at the beginning of every PHP script, before any HTML output or
whitespace!
The PHP superglobal variable $_SESSION is
used to both store and access the session variables
available to the current script.
Now, let's create a PHP page called "test.php". In this page, we start a new PHP session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Run example »
Retrieve PHP Session Variable Values
Next, we create another PHP page called "test2.php". From this page, we will access the session information we set on the first page ("test.php").
Example
<?php
// Resume the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Output session variables that were set on previous page
if(isset($_SESSION["favcolor"])) {
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
} else {
echo "No session data found.";
}
?>
</body>
</html>
Run example »
How does it work? How does it know it's me?
When a
user visits a page that calls the session_start() function, PHP checks for an
existing session ID in the user's browser. If no session ID
is found, PHP generates a unique, random ID.
This ID (stored in a cookie named PHPSESSID) is the only piece of information stored on the client side. The session data is stored securely on the server, typically in a temporary file.
On the next page load, the server gets the session ID from the cookie and uses it to load the session data into the PHP superglobal $_SESSION. The session data is then available to the current script in all scopes.
Another way to show all the session variable values for a user session is by using print_r($_SESSION):
Example
<?php
// Resume the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Run example »
Modify a PHP Session Variable
To change a session variable, just overwrite it:
Example
<?php
// Resume the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Run example »
Destroy a PHP Session
Next, we create another PHP page called "logout.php". Here we will
unset all session variables and destroy the session (with
session_unset()
and session_destroy()):
Example
<?php
// Resume the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
//
Unset all session variables
session_unset();
//
Destroy the session
session_destroy();
echo "You have been logged
out."
?>
</body>
</html>
Run example »
PHP Sessions vs. Cookies
Here are the key differences between sessions and cookies:
| Session | Cookies |
|---|---|
| The data is stored on the server | The data is stored in the browser |
| Expires when the browser is closed, or after a user has been inactive for some time | Can have a long expiration date |
| More secure, since data is not stored in the browser | Less secure, since data is stored in the browser |
| More efficient, does not require constant data transfer between browser and server | Less efficient, since data is sent with each request |