Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Using sessions in PHP

Thursday, January 17th, 2013 by Servage

There are two ways how you can store data associated with a given visitor. You can use cookies on the client or sessions on the server. In this article I will present you with the basic concepts of sessions usage in PHP. First of all, it works so that PHP stores a cookie on the client side with a session ID. This session ID is then used to identify and retrieve a session stored on the server. So you can actually store secret information in the session and be sure it isn’t manipulated or seen by the user – unlike cookies which are viewable by the browser.

Start the session

Before you can use the session, you must start it. PHP includes a lot of different options. You can read about them here. I have simple included a few sample options in the example below, to give you a feeling for how it’s done. Please note that this code must be at the beginning of your code, before trying to access the session. Otherwise you get an error.

ini_set('session.name', 'sessionId');
ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 0);
ini_set('session.cookie_lifetime', 0);
ini_set('session.save_path', ROOT.'Temporaries/sessions');
session_start();

Using the session

When you activated the session, it’s really easy to use it. PHP has included magic global variables to handle it, similarly to GET or POST parameters. You can read and write data to/from the session like this:

$_SESSION['foo'] = bar;
echo $_SESSION['foo'];

Sessions are your powerful friends to store temporary data on a per-user basis. Have fun :-)

Using sessions in PHP, 3.0 out of 5 based on 2 ratings
Categories: Servage
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.