Last Updated:

Session management in PHP

Session management in PHP

What is session management?

 

HTTP is sometimes referred to as the "stateless protocol". This means that this protocol does not have a built-in way of maintaining state between two transactions. When a user requests two pages after another, HTTP does not provide a way to notify that both requests originate from the same user. Thus, the idea behind session management is to ensure that the user is tracked during a single session with a Web site. If this can be done, we will be able to easily maintain the user's connection and the provision of the content of the site to him in accordance with his level of access rights or personal settings. We will be able to track user behavior.

In earlier versions of PHP, session management was done using PHPLib, the base PHP library, which is now a useful set of tools. You can read about it at

The fourth version of PHP includes its own built-in session management functions. Conceptually, they are similar to PHPLib, but PHPLib also provides em and a number of additional functionality. So if it turns out that these native functions do not quite meet your requirements, there is nothing to prevent you from considering using PHPLib.

Basic functional session management tools. 

To start a session, PHP uses a unique session identifier, which is an encrypted random number. The session ID is generated by the PHP and stored on the client for the lifetime of the session. To store the session ID, either a cookie set on the user's computer or a URL is used.

The session identifier acts as a key that allows you to register some specific variables as so-called session variables. The contents of these variables are stored on the server. The only information "visible" on the client side is the session ID. If, during a particular connection to your site, the session ID is "visible" either in the cookie set or in the URL, it is possible to access the session variables that are stored on the server for that session. By default, session variables are stored in two-dimensional files on the server (if you prefer, you can change the storage method and use a database instead of a two-dimensional file, but you will need to write your own function).

You will most likely have to deal with Web sites that use a URL to store the session ID. If you have a string of data in your URL that looks random, then this is most likely indicative of using one of the two variations of session control described here.

Another solution to the problem of preserving state over a certain number of transactions, if there is a clean appearance of the URL, are cookie sets.

What is a cookie? 

 

A cookie is a small piece of information that scripts store on a client machine. To set a cookie set on a user's machine, you must send the user an HTTP header that contains data in the following format.

Set-Cookie: NAME=VALUE; [expires=DATE;] [path=PATH;] [domain=DOMAIN_NAME;] [secure]

This will create a cookie set named NAME and VALUE. All other parameters are optional. Expires sets the expiration date after which the cookie will no longer be considered relevant. Note that if no expiration date is set, the cookie will remain persistent until someone manually deletes it —either you or the user). The two path and domain parameters are used to define one or more URLs to which this cookie belongs. The secure keyword means that the cookie cannot be sent over a simple HTTP connection.

When a browser connects to a URL, it first looks for cookies stored locally. If any of them relate to the URL to which the connection is established, they are transmitted back to the server.

Setting cookies from PHP. 

Cookie sets in PHP can be set manually using the setcookie() function. It has the following prototype:

int setcookie (string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

The parameters correspond exactly to those used in the Set-Cookie heading described above. If the cookie set is set to

setcookie ("mycookie", "value");

then when a user accesses the next page on your site (or reloads the current page), you access a variable named $mycookie that contains the value "value". This variable can also be accessed through the $HTTP_COOKIE_VARS["mycookie"].

To delete a cookie set, you must call setcookie() with the same name, but without specifying a value. If the cookie was set with different parameters (such as specific URLs or expiration dates), you will need to resend the same settings, otherwise the cookie will not be deleted.

To set a cookie set manually, you can also use the Header() function and the cookie set syntax described above. However, keep in mind that cookie headers must be sent before all other headers (otherwise cookie headers will not work).

Use of cookies in sessions. 

When using cookie sets, some problems arise: there are browsers that do not accept cookie sets, and there are users who prohibit the use of cookie sets in their browsers. This is one of the reasons why PHP sessions use the dual cookie/URL method (this is discussed in more detail below).

There is no need to set cookies manually in a PHP session. The session features will do it for you. To view the contents of the cookie set set when managing a session, you can use the session_get_cookie_params() function. It returns an associative array containing the lifetime, path, and domain elements.

You can also use:

session_set_cookie_params($lifetime, $path, $domain);

This statement sets the cookie settings for the session.

If you would like more information about cookies, please visit the Netscape website for advice on the specification of cookies:

Save the session ID. 

In PHP, session cookies are used by default. If it is possible to set cookies, this method will be used to save the session ID. Another method that can be used in PHP is to add a session ID to the URL. You can make the session ID appended to the URL automatically by compiling the PHP with the --enable-trans-sid option.

You can embed a session ID in a link to ensure that it is transmitted. The session ID will be remembered in the SID constant. In order to pass it manually, you will need to add it to the end of the link, similar to the GET parameter:

<A HREF="link.php?<?=SID?>">

In general, it is easier to compile PHP with --enable-trans-sid if possible (note in passing that the SID constant can only be used for the purposes described above if the PHP configuration was performed with --epakle-track-vars).

Implement simple session management. 

The main steps in using a session are as follows:

  • Start a session
  • Registering Session Variables
  • Using Session Variables
  • Unregister variables and close a session

Note that all of these steps may not necessarily be contained in a single scenario, and some of them may be in multiple scenarios. Let's look at each of these steps sequentially.

Start a session. 

Before you can use the functionality of a session, you must start the session itself. There are three ways to do this.

The first (and simplest) is that the script starts with a function call

session_start() ;

This function checks whether the id of the current session exists. If not, she creates it. If the current session ID already exists, it loads the registered session variables so that they are available for use.

To be sure, this is a great way to call session_start() at the beginning of scripts that use sessions.

The second way is that the session starts when you try to register session variables (see below).

The third way to start a session is to set PHP settings, which will start the session automatically as soon as someone visits your site. To do this, use the session.auto_start option in the php.ini file (this method will be described in more detail when considering the configuration).

Register session variables.

In order to be able to track variables from one script to another, they must be registered. This is done by calling the session_register() function. For example, the following code is used to register a variable $myvar.

$myvar = 5; session_register("myvar");

Note that you must pass a string containing the variable name to the session_register() function. This string must not include the $ character. This statement registers the name of the variable and tracks its value. The variable will be tracked until the session ends or until it is manually unregistered.

You can register more than one variable in one step by passing in a comma-separated list of variable names:

session_register("myvar1", "myvar2");

Use session variables. 

To make a session variable available for use, you must first start the session by using one of the methods described above. After that, you have access to this variable. If the register_globals option is enabled, the variable can be accessed through an abbreviated form of its name, such as $myvar. If this option is not enabled, you can access the variable through the associative array $HTTP_SESSION_VARS, for example, $HTTP_SESSION_VARS ["myvar"].

Session variables cannot be overwritten with GET or POST data. This is good from a security point of view, but comes with some coding limitations.

On the other hand, you will need to be careful when checking whether session variables are already set (for example, using isset() or empty()). Also, keep in mind that variables can be set by the user via GET or POST. To check whether the variable is a registered session variable, you can access the session_is_registered() function. The function call is as follows:

$result = session_is_registered("myvar");

This function will check whether $myvar registered session variable and return true or false. You can do something else - check the array $HTTP_SESSION_VARS for the presence of a variable in it.

Unregister variables and end the session.

After you are finished working with a session variable, you can unregister it by using the

session_unregister("myvar");

Like the registration function, this function requires that you specify the name of the variable that you want to unregister as a string that does not include the $ character. This function can unregister only one session variable at a time (as opposed to session_register()). However, to unregister all variables of the current session, you can refer to the session_unset().

At the end of the session, you will first need to unregister all variables and then call to reset the session id

session_destroy();

An example of a simple session. 

The above material may seem somewhat abstract, so now we offer you an example. The code in it handles three pages. On the first page, we'll start the session and register the variable $sess_var The code shown in Listing 6.15.

Code Listing 6.15. page1.php - Start a session and register a variable

<?

session_start ();

session_register("sess_var");

$sess_var = "Hello world!";

echo "The content of \ $sess_var is $sess_var<br>" ;

?>

<a href = "page2.php">Next page</a>

We registered the variable and set its value.

Note that we changed the value of the variable after registering it. You can, however, do the opposite— set a value, and then register the variable. The final value of a variable on a page is the value that will be available on subsequent pages. At the end of the script, the session variable is converted to sequential form (serialized), or frozen, until it is rebooted through the next call to session_start(). Therefore, the following scenario begins by calling session_start(). The script is shown in Listing 6.16

Code Listing 6.16. page2.php - Access the Session Variable and Unregister

<?

session_start();

echo "The content of \ $sess_var is $sess_var<br>";

session_unregister("sess_var");

?>

<a href = "page3.php">Next page</a>

When session_start() is called, the variable $sess_var will be available and its value will be the one stored in the previous session.

Having done all the necessary actions with the variable, we call the session_unregister() to unregister it. Note that the session still exists, but the variable $sess_var is no longer registered.

Finally, we move on to page3.php, the last scenario in this example.

Code Listing 6.17. page3.php - End Session

<?

session_start();

echo "The content of \ $sess_var is $sess_var<br>";

session_destroy () ;

?>

As you can see, the $sess_var value can no longer be accessed. And finally, call session_destroy() to destroy the session ID.

Configure session management. 

And now we offer you to familiarize yourself with a set of configuration options for sessions that you can set in your php.ini file. In Table. Figure 7.8 lists some of the most useful options along with a brief description of them.