PHP Session Variables -Setting and Using

After you create a session with session_start(), you can use session variables. PHP Session variables allow you to use data across webpages and implement coding logic in your web application . The PHP Session Variables can be used after they are declared and initialized. The session variables can also be registered before using them(in versions earlier than PHP 6.0).

Using $_SESSION superglobal

HTTP is stateless and to overcome this limitation, session variables are used to manipulate data between different pages of a web application. After starting session you can use $_SESSION superglobal to initialize the required variables. The values of these session variables can be updated in any web page just like value of a variable. 

The required variable is declared and initialized by writing the  name of the variable name in $_SESSION superglobal. This is given in [] parenthesis as shown as a key of the superglobal array $_SESSION .

$_SESSION[‘var_name’]=value

Example
$_SESSION['userName']='Smith';
$_SESSION['vistorCount']=100;

Registering PHP Session Variables

The second way and the lesser used mechanism for using the PHP Session Variables is by registering them. It is done by calling the session_register function. This method is available only in versions before PHP 6.0.This method can be used instead of setting the variables with superglobals $_SESSION.

$var_name=value; 
$reg_var_name=’var_name’;
Session_register($reg_var_name);
Example
<?php 
$user_name = 'Smith Jones;
$regname = 'user_name';
session_register($regname);
?>

After the variable user_name is registered it can be used as $user_name.

Session Variable Set- Checking

Many times you may need to check whether a particular variable is initialized or not. This is a good thing to do to prevent unexpected errors due to missing variable values. To test this you simply have to check the session variable in  if condition statement. It is shown as below

if (!$_SESSION[‘variable_name’]){  }  else { }

If the variable is already initialised using $_SESSION superglobal, if condition will return true else it will return false. (! NOT operator is mentioned before $_SESSION)

Accessing the Session Variables

The session variables initialized with superglobal $_SESSION can be accessed like any PHP variable. It must be give on the right hand side of assignment operator. On the left hand side the PHP variable is given to store this value.

$var_name=$_SESSION[‘varName’]; For example if you want to increment the viewers count for a web page you can use the following code.

<?PHP
$currCount=$_SESSION['user_count'];
$currCount=$currCount+1;
$_SESSION['user_count']= $currCount;
?>

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *