Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST

PHP Tutorial

PHP HOME PHP Intro PHP Install PHP Syntax PHP Comments PHP Variables PHP Echo / Print PHP Data Types PHP Strings PHP Numbers PHP Casting PHP Math PHP Constants PHP Magic Constants PHP Operators PHP If...Else...Elseif PHP Switch PHP Loops PHP Functions PHP Arrays PHP Superglobals PHP RegEx PHP RegEx Functions

PHP Forms

PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail PHP Form Complete

PHP Advanced

PHP Date and Time PHP Include PHP File Handling PHP File Open/Read PHP File Create/Write PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions

PHP OOP

PHP What is OOP PHP Classes/Objects PHP Constructor PHP Destructor PHP Access Modifiers PHP Inheritance PHP Constants PHP Abstract Classes PHP Interfaces PHP Traits PHP Static Methods PHP Static Properties PHP Namespaces PHP Iterables

MySQL Database

MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data

PHP XML

PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat PHP XML DOM

PHP - AJAX

AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll

PHP Examples

PHP Examples PHP Compiler PHP Quiz PHP Exercises PHP Server PHP Syllabus PHP Study Plan PHP Certificate

PHP Reference

PHP Overview PHP Array PHP Calendar PHP Date PHP Directory PHP Error PHP Exception PHP Filesystem PHP Filter PHP FTP PHP JSON PHP Keywords PHP Libxml PHP Mail PHP Math PHP Misc PHP MySQLi PHP Network PHP Output Control PHP RegEx PHP SimpleXML PHP Stream PHP String PHP Variable Handling PHP XML Parser PHP Zip PHP Timezones

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 variables
  • unset() - Removes a specific session variable (e.g unset($_SESSION["favcolor"]))
  • session_destroy() - Destroys all data associated with the current session
  • session_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


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->