A large PHP application consists of multiple PHP files that logically separate functionality and provide for easier interpretation and maintenance. However, when a Web server loads a new PHP file, it begins a new program from scratch and loses the values in any variables created by the former PHP file. To store data and share it among PHP files in an application, you create a PHP session. Use the default PHP name for the session, or name the session yourself.
Create a new PHP file with an editor. For example, type:
Call the "session_name" function to set the session name and then call the "session_start" function to create the session. For example, type:
if (!session_start()) die("Could not create session!");
Store data for use within the session in the special "$_SESSION" array. Redirect the program to a different PHP file. For example, type:
$_SESSION["id"] = $form_input_id;
$_SESSION["email"] = $form_input_email;
Exit the editor and save the file. Create a new PHP file, "supplemental.php," with the editor. For example, type:
Call "session_name" and then "session_start" to continue the session. Retrieve and output the session data saved by the previous PHP file. For example, type:
if (!session_start()) die("Could not continue session!");
$email = $_SESSION["email"];
printf("<p>Your id is %s</p><p>Your email is %s</p>", $id, $email);
Exit the editor and save the file. Use a browser to navigate to the "main.php" file and run it to test the program logic.
Tips & Warnings
- Session names should consist of letters and numbers only, have at least one letter and not contain any spaces.
- Take additional precautions, such as using cookies to store session data, in order to make certain that the information stored in a session is only accessed by the user who created the session.
How to Create and Use $_SESSION in PHP
In a nutshell, $_SESSION is a type of variable used in the PHP programming language to store information on a website across...