You are on page 1of 15

Starting a Session

To work with a session, you need to explicitly start or resume that session
unless you
have changed your php.ini configuration file. By default, sessions do not
start
automatically. If you want to start a session this way, you must find the
following
line in your php.ini file and change the value from 0 to 1 (and restart the
web
server):
session.auto_start = 0
By changing the value of session.auto_start to 1, you ensure that a session
initiates
for every PHP document. If you dont change this setting, you need to call
the
session_start() function in each script.
After a session is started, you instantly have access to the users session ID
via the
session_id() function. The session_id() function enables you to either set or
retrieve a session ID. Listing 12.2 starts a session and prints the session ID
to the
browser.
LISTING 12.2 Starting or Resuming a Session
1: <?php
2: session_start();
3: echo <p>Your session ID is .session_id()..</p>;
4: ?>
When this script (lets call it session_checkid.php) is run for the first time
from a
browser, a session ID is generated by the session_start() function call on line
2. If
the script is later reloaded or revisited, the same session ID is allocated to
the user.
This action assumes that the user has cookies enabled. For example, when I
run this
script the first time, the output is as follows:
Your session ID is 8jou17in51d08e5onsjkbles16.
When I reload the page, the output is still
Your session ID is 8jou17in51d08e5onsjkbles16.
because I have cookies enabled and the session ID still exists.

Working with Session Variables


Because start_session() attempts to set a cookie when initiating a session
for the
first time, it is imperative that you call this function before you output
anything else
at all to the browser. If you do not follow this rule, your session will not be
set, and
you will likely see warnings on your page.
Sessions remain current as long as the web browser is active. When the user
restarts
the browser, the cookie is no longer stored. You can change this behavior by
altering
the session.cookie_lifetime setting in your php.ini file. The default value is 0,
but you can set an expiry period in seconds.
Working with Session Variables
Accessing a unique session identifier in each of your PHP documents is only
the start
of session functionality. When a session is started, you can store any
number of variables
in the $_SESSION superglobal and then access them on any session-enabled
page.
Listing 12.3 adds two variables into the $_SESSION superglobal: product1
and
product2 (lines 3 and 4).
LISTING 12.3 Storing Variables in a Session
1: <?php
2: session_start();
3: $_SESSION[product1] = Sonic Screwdriver;
4: $_SESSION[product2] = HAL 2000;
5: echo The products have been registered.;
6: ?>
The magic in Listing 12.3 will not become apparent until the user moves to a
new
page. Listing 12.4 creates a separate PHP script that accesses the variables
stored in
the $_SESSION superglobal.
LISTING 12.4 Accessing Stored Session Variables
1: <?php
2: session_start();
3: ?>
4: <p>Your chosen products are:</p>
5: <ul>
6: <li><?php echo $_SESSION[product1]; ?></li>
7: <li><?php echo $_SESSION[product2]; ?></li>
8: </ul>
Figure 12.2 shows the output from Listing 12.4. As you can see, you have
access to
the $_SESSION[product1] and $_SESSION[product2] variables in an
entirely
new page.

Although not a terribly interesting or useful example, the script does show
how to
access stored session variables. Behind the scenes, PHP writes information
to a temporary
file. You can find out where this file is being written on your system by using
the session_save_path() function. This function optionally accepts a path to
a
directory and then writes all session files to it. If you pass it no arguments, it
returns
a string representing the current directory to which it saves session files. On
my
system, the following prints /tmp:
echo session_save_path();
A glance at my /tmp directory reveals a number of files with names like the
following:
sess_fa963e3e49186764b0218e82d050de7b
sess_76cae8ac1231b11afa2c69935c11dd95
sess_bb50771a769c605ab77424d59c784ea0
Opening the file that matches the session ID I was allocated when I first ran
Listing
12.2, I can see how the registered variables have been stored:
product1|s:17:Sonic Screwdriver;product2|s:8:HAL 2000;
When a value is placed in the $_SESSION superglobal, PHP writes the
variable name
and value to a file. This information can be read and the variables
resurrected
lateras you have already seen. After you add a variable to the $_SESSION
superglobal,
you can still change its value at any time during the execution of your
script, but the altered value is not reflected in the global setting until you
reassign
the variable to the $_SESSION superglobal.

The example in Listing 12.3 demonstrates the process of adding variables to


the
$_SESSION superglobal. This example is not very flexible, however. Ideally,
you
should be able to register a varying number of values. You might want to let
users
pick products from a list, for example. In this case, you can use the
serialize()
function to store an array in your session.
Listing 12.5 creates a form that allows a user to choose multiple products.
You use
the session variables to create a rudimentary shopping cart.
LISTING 12.5 Adding an Array Variable to a Session Variable
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Storing an array with a session</title>
</head>
<body>
<h1>Product Choice Page</h1>
<?php
if (isset($_POST[form_products])) {
if (!empty($_SESSION[products])) {
$products = array_unique(
array_merge(unserialize($_SESSION[products]),
$_POST[form_products]));
$_SESSION[products] = serialize($products);
} else {
$_SESSION[products] = serialize($_POST[form_products]);
}
echo <p>Your products have been registered!</p>;
}
?>
<form method=post action=<?php echo $_SERVER[PHP_SELF]; ?>>
<p><label for=form_products>Select some products:</label><br />
<select id=form_products name=form_products[] multiple=multiple
size=3>
<option value=Sonic Screwdriver>Sonic Screwdriver</option>
<option value=Hal 2000>Hal 2000</option>
<option value=Tardis>Tardis</option>
<option value=ORAC>ORAC</option>
<option value=Transporter bracelet>Transporter bracelet</option>
</select></p>
<button type=submit name=submit value=choose>Submit
Form</button>
</form>
<p><a href=session1.php>go to content page</a></p>
</body>
</html>
The listing starts or resumes a session by calling session_start() on line 2.
This
call gives access to any previously set session variables. An HTML form
begins on
line 24 and, on line 26, creates a SELECT element named form_products[],
which
contains OPTION elements for a number of products.
Remember that HTML form elements that allow multiple selections, such as
check
boxes and multiple select lists, should have square brackets appended to
the
value of their NAME attributes. This makes the users choices available to
PHP in
an array.
The block of PHP code beginning on line 11 tests for the presence of the
$_POST[form_products] array (line 12). If the variable is present, you can
assume that the form has been submitted and information has already been
stored
in the $_SESSION superglobal.
Line 12 tests for an array called $_SESSION[products]. If the array exists, it
was
populated on a previous visit to this script, so the code merges it with the
$_POST[form_products] array, extracts the unique elements, and assigns
the
result back to the $products array (lines 1416). Then the $products array is
added
to the $_SESSION superglobal on line 17.
Line 35 contains a link to another script, which will demonstrate access to
the products
the user has chosen. This new script is created in Listing 12.6, but in the
meantime
you can save the code in Listing 12.5 as arraysession.php.
Moving on to Listing 12.6, you see how to access the items stored in the
session created
in arraysession.php.
LISTING 12.6 Accessing Session Variables
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Accessing session variables</title>
</head>
<body>
<h1>Content Page</h1>
<?php
if (isset($_SESSION[products])) {
echo <strong>Your cart:</strong><ol>;
foreach (unserialize($_SESSION[products]) as $p) {
echo <li>.$p.</li>;
}
echo </ol>;
}
?>
<p><a href=arraysession.php>return to product choice page</a></p>
</body>
</html>
Once again, session_start() resumes the session on line 2. Line 12 tests for
the
presence of the $_SESSION[products] variable. If it exists, the variable is
unserialized
and looped through on lines 1416, printing each of the users chosen items
to the browser.
For a real shopping cart program, of course, you would keep product details
in a
database and test user input, rather than blindly store and present it, but
Listings
12.5 and 12.6 demonstrate the ease with which you can use session
functions to
access array variables set in other pages.

Destroying Sessions and Unsetting Variables


You can use session_destroy() to end a session, erasing all session variables.
The
session_destroy() function requires no arguments. You should have an
established
session for this function to work as expected. The following code fragment
resumes a session and abruptly destroys it:
session_start();
session_destroy();
When you move on to other pages that work with a session, the session you
have
destroyed will not be available to them, forcing them to initiate new
sessions of their
own. Any registered variables will be lost.
The session_destroy() function does not instantly destroy registered
variables,
however. They remain accessible to the script in which session_destroy() is
called
(until it is reloaded). The following code fragment resumes or initiates a
session and
registers a variable called test, set to 5. Destroying the session does not
destroy the
registered variable:
session_start();
$_SESSION[test] = 5;
session_destroy();
echo $_SESSION[test]; // prints 5
To remove all registered variables from a session, you simply unset the
variable:
session_start();
$_SESSION[test] = 5;
session_destroy();
unset($_SESSION[test]);
echo $_SESSION[test]; // prints nothing (or a notice about an undefined
index)

Using Sessions in an Environment with Registered Users


The examples youve seen so far have gotten your feet wet with sessions,
but perhaps
additional explanation is warranted for using sessions in the wild, so to
speak. The following two sections outline some examples of common
session usage.
In later chapters of this book, sessions are used in the sample applications
you
build.
Working with Registered Users
Suppose that youve created an online community, or a portal, or some
other type of
application that users can join. The process usually involves a registration
form,
where the user creates a username and password and completes an
identification
profile. From that point forward, each time a registered user logs in to the
system,
you can grab the users identification information and store it in the users
session.
The items you decide to store in the users session should be those items
you can
imagine using quite a bitand that would be inefficient to continually
extract from
the database. For example, suppose that you have created a portal in which
users
are assigned a certain level, such as administrator, registered user,
anonymous
guest, and so forth. Within your display modules, you would always want to
check
to verify that the user accessing the module has the proper permissions to
do so.
Thus, user level is an example of a value stored in the users session, so
that the
authentication script used in the display of the requested module only has
to check
a session variablethere is no need to connect to, select, and query the
database.
Working with User Preferences
If you are feeling adventurous in the design phase of a user-based
application, you
might build a system in which registered users can set specific preferences
that affect
the way they view your site. For example, you might allow your users to
select from
a predetermined color scheme, font type and size, and so forth. Or, you
might allow
users to turn off (or on) the visibility of certain content groupings.
You can store each of those functional elements in a session. When the user
logs in,
the application loads all relevant values into the users session and reacts
accordingly
for each subsequently requested page. Should the user decide to change
her preferences,
she could do so while logged inyou could even prepopulate a
preferences
form based on the items stored in the session instead of going back to the
database to retrieve them. If the user changes any preferences while she is
logged in,
simply replace the value stored in the $_SESSION superglobal with the new
selection
no need to force the user to log out and then log back in again.

Summary
In this chapter, you looked at different ways of saving state in a stateless
protocol,
including setting a cookie and starting a session. All methods of saving state
use
some manner of cookies or query strings, sometimes combined with the use
of files
or databases. These approaches all have their benefits and problems.
You learned that a cookie alone is not intrinsically reliable and cannot store
much
information. However, it can persist over a long period. Approaches that
write information
to a file or database involve some cost to speed and might become a
problem
on a popular site; this is a matter to explore with your systems
administrators.
About sessions themselves, you learned how to initiate or resume a session
with
session_start(). When in a session, you learned how to add variables to the
$_SESSION superglobal, check that they exist, unset them if you want, and
destroy
the entire session.

Q&A
Q. What will happen to my application if users disable cookies?
A. Simply put, if your application relies heavily on cookies and users have
cookies
disabled, your application wont work. However, you can do your part to
warn users that cookies are coming by announcing your intention to use
cookies,
and also by checking that cookies are enabled before doing anything
important with your application. The idea being, of course, that even if
users ignore your note that cookies must be turned on in order to use your
application, specifically disallowing users to perform an action if your cookie
test fails will get their attention!
Q. Should I be aware of any pitfalls with session functions?
A. The session functions are generally reliable. However, remember that
cookies
cannot be read across multiple domains. So, if your project uses more than
one domain name on the same server (perhaps as part of an e-commerce
environment), you might need to consider disabling cookies for sessions by
setting
the
session.use_cookies
directive to 0 in the php.ini file.
Workshop
The workshop is designed to help you review what youve learned and begin
putting
your knowledge into practice.
Quiz
1. Which function would you use to start or resume a session within a PHP
script?
2. Which function can return the current sessions ID?
3. How can you end a session and erase all traces of it for future visits?
Answers
1. You can start a session by using the session_start() function within your
script.
2. You can access the sessions ID by using the session_id() function.
3. The session_destroy() function removes all traces of a session for future
requests.
Activities
. Create a script that uses session functions to track which pages in your
environment
the user has visited.
. Create a new script that will list for the user all the pages she has visited
within
your environment, and when.

<?php
session_start();
if( isset( $_SESSION['counter'] ) ) {
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>

</html>

The following example demonstrates how to register a variable, and how to link
correctly to another page using SID.

<?php
session_start();
if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}else {
$_SESSION['counter']++;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";

echo ( $msg );
?>
<p>
To continue click following link <br />

<a href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">


</p>
Iniciando uma sesso em PHP
necessrio utilizar a funo session_start para iniciar qualquer sesso em PHP. Voc
deve chamar essa funo antes de qualquer output do seu cdigo, ou seja, antes de
qualquer echo, print, cdigos HTML e coisas do tipo. Geralmente, chamamos a funo
session_start nas primeiras linhas do nosso cdigo PHP para prevenir erros.

// Inicia a sesso
session_start();

Definindo valores para $_SESSION

<?php
// Inicia a sesso
session_start();

// Cria as chaves e seus valores


$_SESSION['nome'] = 'Luiz Otvio';
$_SESSION['usuario'] = 'luiz';
$_SESSION['senha'] = 'otavio';

// Mostra uma frase na tela


echo 'Ol ' . $_SESSION['nome'];

Se eu quiser acessar os dados da sesso em outros arquivos PHP dentro do meu


script, basta iniciar a sesso e exibir os dados.

<?php
// Inicia a sesso
session_start();

// Mostra uma frase na tela


echo 'Ol ' . $_SESSION['nome'];

Perceba que no estou verificando se a sesso existe. Se eu quiser mais segurana eu


meu script, basta verificar se a sesso existe, se no est vazia, e se igual ao usurio
que est na minha base de dados (vamos ver isso mais adiante nesse curso). Veja um
exemplo bsico:

<?php
// Inicia a sesso
session_start();

// Verifica se a sesso do usurio no existe


if ( ! isset( $_SESSION['usuario'] ) && ! isset( $_SESSION['senha'] ) ) {
// Ao a ser executada: mata o script e manda uma mensagem
exit('Usurio no est logado');
}

// Verifica se a sesso do usurio est vazia


if ( empty( $_SESSION['usuario'] ) && empty( $_SESSION['senha'] ) ) {
// Ao a ser executada: mata o script e manda uma mensagem
exit('Sesso terminada, faa login novamente');
}
// Simulao de um usurio do banco de dados
$usuario_bd = 'luiz';

// Verifica se a sesso do usurio est vazia


if ( $_SESSION['usuario'] != $usuario_bd ) {
// Ao a ser executada: mata o script e manda uma mensagem
exit('Voc no o usurio correto.');
}

/*
* Se o seu cdigo passar por todas as verificaes acima
* significa que a sesso existe, no est vazia
* e que o usurio o "luiz"
* portanto, exibimos os dados na tela
*/
echo 'Ol ' . $_SESSION['nome'] . ', acesse seus dados abaixo.';

Apagando valores de $_SESSION

<?php
// Inicia a sesso
session_start();

// Cria uma chave e valor para um item da sesso


$_SESSION['usuario'] = 'luiz';

// Mostra o valor
echo $_SESSION['usuario'];

// Apaga a chave
unset( $_SESSION['usuario'] );

// Tenta mostrar o valor


// Mas gera um erro, pois ela foi apagada
echo $_SESSION['usuario'];

Existem duas formas para apagar todos os dados da sesso, o mais simples atribuir
um array nulo para $_SESSION. Veja:

<?php
// Inicia a sesso
session_start();

// Apaga tudo da sesso


$_SESSION = array();

Note que a sesso ainda estar disponvel, porm vazia.

O segundo mtodo destruindo a sesso, neste caso, a sesso deixar de existir.

<?php
// Inicia a sesso
session_start();

// Destroi a sesso
session_destroy();
Before showing you code, let me tell you some in built PHP functions
which comes handy in session tracking.

session_start()

isset()

unset()

To handle session, you must first start it and store some value to any
session variable. You can create any amount of session variable you
wish. To validate whether Session is active or not, we use
isset() function and finally to destroy it we use unset() function.
Here is our login.php:
<?php
if(isset($_POST['user_name']))
{
session_start();
$_SESSION['name']=$_POST['user_name'];
//Storing the name of user in SESSION variable.
header("location: profile.php");
}
?>
< html>
<head>
<title>Session Handling in PHP - CodeforGeek Demo's</title>
</head>
<body>
<form action="" method="post" id="main_form">
<input type="text" name="user_name"
size="40"><br />
<input type="submit" value="Log in">

</form><br><br>
</body>
< /html>
After submitting the form, we are storing the name of user in session and
in next page we are going to use the same name. This is how most of
web projects do. Now here is a code for profile.php.
<?php
session_start();
if(!isset($_SESSION['name']))
{
header("location: index.php");
}
$name=$_SESSION['name'];
?>
< html>
< head>
< title>Profile of <?php echo $name;?></title>
< /head>
< h1>Hello <?php echo $name;?></h1>
< h3><a href="logout.php">Click here to log out</a></h3>
< /html>
In this file, first we are checking whether the SESSION is set or not. If
not then we will redirect the user to main page, else we will store the
name of user into variable and displaying it in HTML code.
Finally we let user log out from system and to do here is a code.
<?php
if(isset($_SESSION['name']))
{
unset($_SESSION['name']);
}
echo '<h1>You have been successfully logout</h1>';
?>
index.php
<?php
if(isset($_POST['user_name']))
{
session_start();
$_SESSION['name']=$_POST['user_name'];
header("location: profile.php");
}
?>
<html>
<head>
<title>Session Handling in PHP - CodeforGeek Demo's</title>
</head>
<body>
<h2>Session handling in PHP</h2>
<h3>To use the demo do following</h3>
<ul>
<li>Type in your name and log in</li>
<li>See your profile with your name</li>
<li>Log out to destroy session</li>
</ul>
<form action="" method="post" id="main_form">
<input type="text" name="user_name" size="40" placeholder="Type
in your name"><br />
<input type="submit" value="Log in">
</form><br><br>
<span>Tutorial link : </span>
</body>
</html>

profile.php

<?php
session_start();
if(!isset($_SESSION['name']))
{
header("location: index.php");
}
$name=$_SESSION['name'];
?>
<html>
<head>
<title>Profile of <?php echo $name;?></title>
</head>
<h1>Hello <?php echo $name;?></h1>
<h3><a href="logout.php">Click here to log out</a></h3>
</html>

logout.php
<?php
if(isset($_SESSION['name']))
{
unset($_SESSION['name']);
}
echo '<h1>You have been successfully logout</h1>';
?>

You might also like