How to Start and Clear a Session in PHP
PHP developers use sessions as a way of creating sets of data that can pass from page to page within a website. Sessions make Web applications such as discussion boards possible. Two functions control the starting and stopping of sessions: "session_start()" and "session_destroy()." While the session is in progress, you can retrieve values from Web forms for the session using the "$_SESSION" array, which behaves similarly to "$_GET" and "$_POST." Using the "unset()" function will remove information from the array without stopping the session itself.
Instructions
-
-
1
Go to "Start" on the Windows taskbar and type in the name of a code editor or Notepad. Press the "Enter" key to load the program. Open a PHP file where you wish to start a session. This is usually a login page
-
2
Add the "session_start()" function before any other PHP code on the page, other than comments (lines of code that begin with "//" or "/*"). This function will initialize a session and give it a random ID every time a visitor loads the Web page.
-
-
3
Get session values in the same manner as the "Get" and "Post" form-processing methods. For example, if you send form data including an email address, then the "Email" field in that form requires a name attribute of "email." You can then grab the email address for the session like this:
$_SESSION['email'];
-
4
Delete a session variable using the "unset()" function:
unset($_SESSION);
This deletes the entire "$_SESSION" array, including all values such as "email" or "name" that were taken from any forms the session used.
-
5
Use the "session_destroy()" function to clear and remove the session from the server completely. This function removes all files and other data related to the session, not just the array values.
-
1
References
- PHP: Sessions Introduction
- "PHP for the World Wide Web"; Larry Ullman; 2004
- Photo Credit Jupiterimages/Photos.com/Getty Images