Working with session variables in PHP
Let’s say you are creating a website where users need to login. How do you track a user’s id from page to page, or even verify that a user is logged in when they should be? You can use the global $_SESSION variable!
The $_SESSION is an array where you can store your variable and objects. Try the following example where we store a simple integer called user_id.
Create a file on your web server called write_session.php.
<?php // Start the session. This function call is required for us to work with the global $_SESSION variable session_start(); // Assign a new key of 'user_id' to the value 5 $_SESSION['user_id'] = 5; ?> <a href="read_session.php">Read Session</a>
Now we can access the user_id on other pages in our site! Make another page called read_session.php with the following code in it.
<?php // Start the session. This function call is required for us to work with the global $_SESSION variable session_start(); // Output the user_id value echo ("My user id is ".$_SESSION['user_id']."!"); ?>
Execute the write_session.php page and you should see
My user id is 5!
If you are using your session to store a logged in user’s information it is a good idea to give them a log out option.
Create another file called logout.php
<?php // Required to use the global $_SESSION variable session_start(); // Destroy this session session_destroy(); echo ("Your session has been destroyed!"); ?>
In a later tutorial I will walk you through a complete user authentication process, from login to logout.