Sessions in Php


Session is used to store information about user .
Session variables hold information about one single user, and are available to whole application.

Session Variables

Session allow you to store user information on the server for later use (i.e. username, shopping items, etc).
Sessions work by creating a unique id (session_id) for each visitor and store variables based on this session_id. The session_id is either stored in a cookie or is appended in the URL.

session_id is used to get or set the session id for the current session.
session_id() returns the session id for the current session or the empty string ("") if there is no current session

Start a PHP Session

Before you store  information in your session, you must first start  the session.
Note: The session_start() function must be written BEFORE the <html> tag:
<?php session_start(); ?>

<html>
<body>

</body>
</html>
The code above will register the user's session with the server, allow you to start saving user information, and assign a session_id for that user's session.

Store a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
<?php

session_start();
// store session data
$_SESSION['visits']=1;

?>
<html>
<body>
<?php

//retrieve session data
echo "Pagevisits=". $_SESSION['visits'];
?>

</body>
</html>
Output:
Pagevisits=1
In the example below, we create a simple page-visits counter.
The isset() function checks if the "visits" variable has already been set. If "visits" has been set, we can increment our counter. If "visits" doesn't exist, we create a "visits" variable, and set it to 1:

<?php
session_start(); 
if(isset($_SESSION['visits']))
 $_SESSION['visits']=$_SESSION['visits']+1;
else
 $_SESSION['visits']=1;

echo "visits=". $_SESSION['visits'];
?>

Destroy a Php Session

You can use the unset() or the session_destroy() function to delete some session data.
The unset() function is used to free up the specified session variable:
<?php

session_start();

if(isset($_SESSION['visits']))
  unset($_SESSION['visits']);

?> 
You can completely destroy the session using the session_destroy() function:

<?php
session_destroy();
?>

No comments: