What is Session in php?
session is started with session_start() function.
session_start() :- Start new or resume existing session
Session variables are set with the PHP global variable:
$_SESSION.
session variables are not passed individually to each new
page, instead they are retrieved from the session we open at the
beginning of each page (session_start()).
This function returns TRUE if a session was successfully started, otherwise FALSE.
How to start session in php?
session is started with session_start() function.
The session_start() function must appear BEFORE the
<html>tag.
File Name :
<?php
session_start(); // Start the session
?>
<html>
<body>
</body>
</html>
How to set session variable in php?
<html>
<body>
<?php
// Set
session variables
$_SESSION["fname"] = "mahtab";
$_SESSION["lname"] = "habib";
echo "Session variables are
set.";
?>
</body>
</html>
How to get php session variable values.
<?php
session_start(); ?>
<html>
<body>
<?php
// you can get session variable any pages of your appication.
echo "Your First name is " .
$_SESSION["fname"];
echo "Your Last name is " .
$_SESSION["lname"];
?>
</body>
</html>
/******************** OR ************/
<?php
print_r($_SESSION); // it show all the session variable.
?>
How does it work? How does it know it's me?
Most sessions set a user-key on the user's computer that looks
something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when
a session is opened on another page, it scans the computer for a
user-key. If there is a match, it accesses that session, if not,
it starts a new session.
Modify a PHP Session Variable.
To change a session variable, just overwrite it:
Example
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["fname"] = "sana";
print_r($_SESSION);
?>
</body>
</html>
How to Destroy the session.
To remove all global session variables and destroy the session, use session_unset() and session_destroy().<br>
Example
<?php
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["fname"] = "mahtab";
// Remove session variable
unset($_SESSION['fname']);
// remove all session variables
session_unset();// destroy the session
session_destroy();// destroy the all session.
?>
</body>
</html>
How to check session exist or not.
<?php
session_start();
$_SESSION['login_user']=$myuserid;
if(!isset($_SESSION['login_user']))
{
header("Location: login.php");
}
?>
Logout.
File name logout.php
<?php
session_start();
// remove single session variable data.
unset($_SESSION['login_user']);
// remove all session variables
session_unset();
// destroy the session
session_destroy();
if(!isset($_SESSION['login_user']))
{
//echo "session destroyed";
header("Location: login.php");
}
?>
session_name
session_name - Get and/or set the current session name
syntax : string session_name ([ string $name ] )
session_name() returns the name of the current session. If name is given, session_name() will update the session name and return the old session name.
The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called).
To use a named session, call session_name() before calling session_start().
Parameters
name :- The session name references the name of the session, which is used in cookies and URLs (e.g. PHPSESSID). It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). If name is specified, the name of the current session is changed to its value.
Warning :- The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time.
Return Values :- Returns the name of the current session. If name is given and function updates the session name, name of the old session is returned.
File name logout.php
<?php
/* set the session name to itechtutoid*/
$previous_name = session_name("itechtutoid");
echo "The previous session name was $previous_name<br />";
?>
session_id
syntax :- string session_id ([ string $id ] )
session_id() is used to get or set the session id for the current session.
session_id() needs to be called before session_start() for that purpose. Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 ,
<?php
$a = session_id();
if(empty($a)) session_start();
echo "SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>
<?php
if(!session_id())
{
// Always executed even if there's already an opened session
}
session_id() returns an empty string if there is no current session, so to test if a session already exists, it's better to write this :
if(session_id() == "")
{
session_start();
}
else
{
// Anything you want
}
?>
session_save_path
string session_save_path ([ string $path ] ) br/>
session_save_path() returns the path of the current directory used to save session data.
path :-
Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
.........
?>
How to check user session exists or not.
At the top of each page, check to see if the user is logged in. If not, they should be redirected to a login page:
<?php
if(!isset($_SESSION['logged_in'])) :
header("Location: login.php");
exit();
?>
on logout, simply unset the logged_in session variable, and destroy the session
<?php
unset($_SESSION['logged_in']);
session_destroy();
?>
In login validation script if user is authenticated set one session value for instance as follows:
$_SESSION['status']="Active";
And then in User Profile script put following code snippet:
<?php
session_start();
if($_SESSION['status']!="Active")
{
header("location:login.php");
}
?>
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma", "no-cache");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
// date in the past
the following on each page to prevent page caching:-
Disabling back button is not a right way to achieve your need. Instead you can add the following three tags in your html file, which takes care of clearing cache.
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<META NAME="ROBOTS" CONTENT="NONE">
<META NAME="GOOGLEBOT" CONTENT="NOARCHIVE">
<META Http-Equiv="Cache-Control" Content="no-cache">
<META Http-Equiv="Pragma" Content="no-cache">
<META Http-Equiv="Expires" Content="0">
How to destroy / expire session after X minutes in php
The best solution is to implement a session timeout on your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it on every request:
function sessionTimeout($duration)
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > ($duration * 60))) {
// last request was more than x minutes ago, where x = duration
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
}
$duration = 40; //40 minute as example
sessionTimeout($duration);
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation-
function sessionRegenerate($duration)
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > ($duration * 60)) {
// session started more than x minutes ago, where x = duration
session_regenerate_id(true); // change session ID for the current session an invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
}
$duration = 40; //40 minute as example
sessionRegenerate($duration);
Note: that session.gc_maxlifetime should be at least equal to the life time of this custom expiration handler (40 minutes in this example).
Previous
Next