How to Name a Session in PHP
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.
Instructions
-
-
1
Create a new PHP file with an editor. For example, type:
nano main.php
-
2
Call the "session_name" function to set the session name and then call the "session_start" function to create the session. For example, type:
<?php
session_name("MySession");
if (!session_start()) die("Could not create session!");
-
-
3
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;
header("Location: http://www.example.com/supplemental.php");
?>
-
4
Exit the editor and save the file. Create a new PHP file, "supplemental.php," with the editor. For example, type:
nano supplemental.php
-
5
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:
<?php
session_name("MySession");
if (!session_start()) die("Could not continue session!");
$id= $_SESSION["id"];
$email = $_SESSION["email"];
printf("<p>Your id is %s</p><p>Your email is %s</p>", $id, $email);
?>
-
6
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.
-
1
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.