Professional Documents
Culture Documents
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.
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.
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 />
// Inicia a sesso
session_start();
<?php
// Inicia a sesso
session_start();
<?php
// Inicia a sesso
session_start();
<?php
// Inicia a sesso
session_start();
/*
* 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.';
<?php
// Inicia a sesso
session_start();
// Mostra o valor
echo $_SESSION['usuario'];
// Apaga a chave
unset( $_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();
<?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>';
?>