Home >Backend Development >PHP Tutorial >How Can I Store and Retrieve Session Variables Across Multiple PHP Pages?
To begin, it's crucial to start a session and store a session variable at the very start of a page's execution, without any prior output. This is essential for the session to function correctly.
In the first page, execute the following code:
<?php session_start(); $_SESSION['myvar'] = 'myvalue'; ?>
This code starts a session and assigns the value 'myvalue' to the session variable 'myvar'.
On a subsequent page, use the following code to check if the session variable is set and has the expected value:
<?php session_start(); echo "1"; if (isset($_SESSION['myvar'])) { echo "2"; if ($_SESSION['myvar'] == 'myvalue') { echo "3"; exit; } } ?>
If the session variable is set and has the value 'myvalue', the code will output the following sequence:
1 2 3
The above is the detailed content of How Can I Store and Retrieve Session Variables Across Multiple PHP Pages?. For more information, please follow other related articles on the PHP Chinese website!