473,695 Members | 2,914 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PHP Sessions

5,058 Recognized Expert Expert
Sessions are one of the simplest and more powerful tools in a web developers arsenal. This tool is invaluable in dynamic web page development and it is one of those things every developer needs to know how to use.
This article explains the basics of PHP Sessions.

Basic PHP knowledge is required (variables, arrays and such)
HTML Forms.

What are Sessions?
Sessions are a way of storing data. When developing interactive web applications we often find ourselves in need of a safe place to put certain pieces of information, such as User ID's and names. Somewhere it won’t be lost every time the browser is refreshed or redirected. This is exactly what Sessions do. They store your data on the server, so you can access it at any time, from within any server-side script.
To make this possible a file is created on the server, it is linked to a SessionID that is generated and sent to the browser as a cookie or through the URL as GET data.
Then, any time your browser is refreshed/redirected the server-side code reads this SessionID and loads the information stored in the file on the server.

Why would I use Sessions?
There are endless possible uses for this tool. It is commonly used to keep track of user information, such as Usernames and UserID's.
For example, if you take a look at the top of the Bytes page your are currently on. If you are logged in you will see a welcome message and some user controls. These fields will stay the same no matter where you go on the Bytes web. To make this possible, your user info must be stored somewhere safe, where the server-side script will be able to read it. This is the very reason Sessions exists, to make things like this possible.

How do I use Sessions?
Using Sessions in PHP is very simple. First of all, you need to tell your script that you are going to be using Sessions.
This is done by invoking the start_session() function. This function will either create a new session or re-open an existing one. Because this function needs to send header data to your browser, it must be called before any output is sent.

Once you have told your browser to use sessions, you can access your session data by calling the $_SESSION super-global. This is an array, that works pretty much like any other PHP array. You can add, edit, read and unset it's fields just like you would a normal array.

This is a little example of how to create a session and use the $_SESSION array:
Expand|Select|Wrap|Line Numbers
  1. // Start the session
  2. session_start();
  4. // Create a session variable
  5. $_SESSION['MyVar'] = "This is my session variable";
  7. // Use the session variable
  8. echo "MyVar: ". $_SESSION['MyVar'];
  10. // Edit a session variable
  11. $_SESSION['MyVar'] = "I just edited my first variable";
  13. // Delete a session variable
  14. unset($_SESSION['MyVar']);
Once you have set a field inside the $_SESSION array, it will be available to any server-side script on the web until the browser is closed or until the field is manually unset.

A simple example:
Earlier in the article I talked about storing user data with Sessions. This little example shows how you can gather user information and store it in the PHP Session array.
It simply asks the user for a username through a HTML form and adds it to the Session. Then when the user has logged in, it prints a welcome message and gives the user the option to log out. If the user chooses to log out, it simply unsets the Session field. effectively logging the user out.
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Start the session
  3. session_start();
  5. // Check if a username is stored in the session
  6. if(isset($_SESSION['Username'])) 
  7. {
  8.   // Check if the user has pressed the logout link
  9.   if(isset($_GET['logout'])) 
  10.   {
  11.     // Unset the SESSION variable Username
  12.     unset($_SESSION['Username']);
  13.     echo "You have been logged out <br /> <a href='?'>Continue</a>";
  14.   }
  15.   else 
  16.   {
  17.       // Print the weclome message
  18.       $sUsername = htmlentities($_SESSION['Username']);
  19.       echo "Your are signed in as '{$sUsername}'<br /><a href='?logout=true'>Logout</a>";
  20.   }
  21. }
  22. else
  23. {
  24.   // Check If the user has posted any data
  25.   if(isset($_POST['Username'])) 
  26.   {
  27.     // Set the SESSION variable Username
  28.     $_SESSION['Username'] = $_POST['Username'];
  29.     echo "You have been logged in! <br /><a href='?'>Continue</a>";
  30.   }
  31.   else 
  32.   {
  33.     // Print the login form
  34.     echo '
  35.         <form action="?" method="post">
  36.          Username: <input name="Username" type="text" /><br />
  37.          <input type="submit" value="Login" />
  38.        </form>';
  39.   }
  40. ?>
May 10 '07 #1
3 28233
60 New Member
Clear, concise beginner tutorial, Atli.
My question:
How secure are php sessions? And how reliable? I do not include here a situation where the user has jeopardised private information by, say, failing to log out, and someone else now gets hold of the system (e.g. public computers).
In other words, if I have passed sensitive information into the $_SESSION array, I can just go to sleep with both eyes closed?
Keep it flowing.
Feb 15 '08 #2
5,058 Recognized Expert Expert
Hi. Sorry for the delayed answer.

PHP Session can of course be hacked in a number of ways. If you intend to use them to handle sensitive data you are going to want to add an extra layer of security (or two).

A simple way to make them a little bit more secure is to obtain the IP of the user when first creating the session and matching the saved IP to the current IP. If they do not match, the session ID could have been compromised.

Having the session time-out after a few minutes is also an easy way to improve the security somewhat. The session will time-out by default after some time, but you may want to check that out in your php.ini and make sure.

There is really nothing we can do to prevent users from accessing a session left open by another user on a public computer. From the servers point of view it is still communicating with the same system. The best defense against such problems is a low time-out delay.
Mar 5 '08 #3
45 New Member
We prevent unauthorized users from accessing a session left open simply by causing an automatic logout within a short time. As an example, the SSA website automatically logs you out after 3 minutes from the last POST packet sent unless you input information back into the system. As for the security of php sessions, the problem is that it is always possible to steal a PHP session via MITM / Cookie theft. This problem is best dealt with in the server config, not in PHP.
Feb 26 '23 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

by: The Plankmeister | last post by:
Hi... I'm trying my hardest to understand fully how sessions work and how best to use them. However, all I can find is information that doesn't tell me anything other than that sessions store information between pages, which I knew already. I want to know HOW sessions work! If anybody has any good links to material that explains sessions fully, then please send those links this way! I'm particularly interested in the...
by: jing_li | last post by:
Hi, you all, I am a newbee for php and I need your help. One of my coworker and I are both developing a webpage for our project using php. We have a copy of the same files in different location on the server (in our own accounts on the same machine). When I am testing both versions of our program using the same browser (IE on Windows or Konqueror on Linux) the session variables will mix up and only the latest selection or options will...
by: Maxime Ducharme | last post by:
Hi group We have a problem with sessions in one of our sites. Sessions are used to store login info & some other infos (no objects are stored in sessions). We are using Windows 2000 Server (IIS 5.0) with ASP 3.0 (no .NET on this site). Sometime, data in session is emptied. I say "sometime"
by: Will Woodhull | last post by:
Hi, I'm new here-- I've been reading the group for a couple of days. Nice group; I like the way n00b33 questions are handled. I've been using a Javascript routine in index.html to determine a visitor's browser's capabilities. The Javascript then calls main.php, passing back its findings with a GET string; main.php saves the data as a visitor's profile in $_SESSION elements. It then serves up home.html and any further pages requested...
by: Steve Franks | last post by:
According to the docs you tell ASP.NET to use cookieless sessions by setting a value in the config.web file. However, what if I wanted to determine at run time whether or not I wanted to use cookieless sessions for a particular user, and if so, I'd instruct ASP.NET to turn on cookieless sessions for a particular user session. Is this possible? For example I want to use cookie based sessions by default for all users. But if a user has...
by: D. Shane Fowlkes | last post by:
This is a repost (pasted below). Since my original post, I've double checked the system clock and set all IIS Session Timeout values to 10 minutes. Still ...the problem occurs. I've also installed Deep Metrix Live Stats 6.2 XPS just to make sure nothing really strange was going on was going on. Still....the sessions only increment...or should I say my counter in my asax file.... and never goes down. If it matters, this machine is...
by: Daniel Walzenbach | last post by:
Hi, I have a web application which sometimes throws an “out of memory” exception. To get an idea what happens I traced some values using performance monitor and got the following values (for one day): \\FFDS24\ASP.NET Applications(_LM_W3SVC_1_Root_ATV2004)\Errors During Execution: 7 \\FFDS24\ASP.NET Apps v1.1.4322(_LM_W3SVC_1_Root_ATV2004)\Compilations
by: magic_hat60622 | last post by:
Hi all. I've got an app that dumps a user id into a session after successful login. the login page is http://www.mydomain.com/login.php. If the user visits pages on my site without the www (i.e., http://mydomain.com/foo.php), the session works fine and login state is maintained. If he visits http://www.mydomain.com/foo.php, the app drops the logged-in state.
by: Frinavale | last post by:
One of the most fundamental topics in web design is understanding how to pass information collected on one web page to another web page. There are many different ways you could do this: Cookies, Database... However, I'm going to cover how to use Sessions. Sessions are used to store information in order to use it during later page requests or in other web pages in a web application. By default Cookies are used to identify which session...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.