Session variable is used to store information.Session variables hold information about one single user, and are available to all pages in one application.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.
Starting a PHP Session
Before using PHP session variable, you must first start the session.
Note: The session_start() function must appear BEFORE the <html> tag:
The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.
Storing a Session Variable
Now you can store and retrieve session variables by using the PHP $_SESSION variable:
<?php
session_start();
// store session data
$_SESSION['visit']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pagevisit=". $_SESSION['visit'];
?>
</body>
</html>
session_start();
// store session data
$_SESSION['visit']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pagevisit=". $_SESSION['visit'];
?>
</body>
</html>
Output:
Pagevisit=1
In the example below, we create a simple page-visit counter. The isset() function checks if the "visit" variable has already been set. If "visit" has been set, we can increment our counter. If "visit" doesn't exist, we create a "visit" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['visit']))
$_SESSION['visit']=$_SESSION['visit']+1;
else
$_SESSION['visit']=1;
echo "Visits=". $_SESSION['visit'];
?>
session_start();
if(isset($_SESSION['visit']))
$_SESSION['visit']=$_SESSION['visit']+1;
else
$_SESSION['visit']=1;
echo "Visits=". $_SESSION['visit'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
session_start();
if(isset($_SESSION['visit']))
unset($_SESSION['visit']);
?>
session_start();
if(isset($_SESSION['visit']))
unset($_SESSION['visit']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
session_destroy();
?>
No comments:
Post a Comment